如何使用FOR循环将数据数组划分为这样的块?

时间:2013-11-21 19:44:39

标签: matlab

如何使用for循环将数据数组划分为这样的块?

请考虑我的示例代码:

a = -1-j;  b = 2-j; % some constants
data = a+(b-a)*rand(1,256); % data
b=[1,2,4,8,16] % number of blocks

如何使用b=[1,2,4,8,16]遍历for的<{1}}循环将我的数据划分为相邻的数据索引分组b,如

out1=1x256=same as data(1x256)(no division into blocks)

out2=[data(1:128) zeros(1,128);zeros(1,128) data(129:256)]; % 2x256

out4=[ data(1:64) zeros(1,192);               % 4x256
       zeros(1,64) data(65:128) zeros(1,128); 
       zeros(1,128) data(129:192) zeros(1,64);
       zeros(1,192) data(193:256)];

out8= [ data(1:32) zeros(1,224);              % 8x256
        zeros(1,32) data(33:64) zeros(1,192);
        zeros(1,64) data(65:96) zeros(1,160);
        zeros(1,96) data(97:128) zeros(1,128)
        zeros(1,128) data(129:160) zeros(1,96);
        zeros(1,160) data(161:192) zeros(1,64);
        zeros(1,192) data(193:224) zeros(1,32);
        zeros(1,224) data(225:256)];

类似地,

out16=[data(1:16) zeros(17,240);             % 16x256
       zeros(1,16) data(17:32) zeros(1,224);
       ...
       ...                                ]

3 个答案:

答案 0 :(得分:2)

无需循环。使用linear indexing来解决需要使用数据写入的条目:

n = 4; %// n arbitrary, but should divide k
k = length(data);
outn = zeros(n,k); %// initialize
cols = 1:k; %// column indices: 1 2 3 ... k
rows = floor(0:n/k:n-n/k)+1; %// row indices: 1 1 ... 1 2 2 ... 2 3 ...
outn(rows+n*(cols-1)) = data; %// write data into those rows and cols

答案 1 :(得分:1)

首先,它需要一个矩阵来指示数据所在的位置:

z=size(data,2);
s=bsxfun(@(x,y)(floor(x)==y),[1:b/z:(b+1-b/z)],[1:b]');

现在我们可以使用此矩阵填写

out=zeros(b,z);
out(s)=data;

完整代码:

a = -1-j;  b = 2-j; z=256; % some constants
data = a+(b-a)*rand(1,z); % data
out={};
for b=[1,2,4,8,16]
    s=bsxfun(@(x,y)(floor(x)==y),[1:b/z:(b+1-b/z)],[1:b]');
    out{end+1}=zeros(b,z);
    out{end}(s)=data;
end

答案 2 :(得分:1)

使用{:}单元格数组索引语法中以逗号分隔的列表,您可以直接使用blkdiag生成输出矩阵。只需使用mat2cell细分data即可。用于b的每个值的循环:

N = numel(data);  % ensure data is a row vector
out={};
for b =  [1 2 4 8 16],
    dataCell = mat2cell(data,1,(N/b)*ones(1,b));
    out{end+1} = blkdiag(dataCell{:});
end