Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide a data arry into blocks like this using a FOR loop?

Tags:

matlab

How to divide a data array into blocks like this using a for loop?

Please consider my sample code:

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

How to divide my data into blocks b=[1,2,4,8,16] in a adjacent grouping of data indices like this using a for loop running over 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)];

Similarly,

out16=[data(1:16) zeros(17,240);             % 16x256
       zeros(1,16) data(17:32) zeros(1,224);
       ...
       ...                                ]
like image 660
user5172 Avatar asked Nov 24 '25 13:11

user5172


2 Answers

No need for a loop. Use linear indexing to address the entries that need to be written with the data:

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
like image 67
Luis Mendo Avatar answered Nov 27 '25 01:11

Luis Mendo


First of all, it requires a matrix which indicates where the data belongs:

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

Now we can use this matrix to fill out

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

Complete code:

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
like image 27
Daniel Avatar answered Nov 27 '25 01:11

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!