Search code examples
arraysmatlabmatrixcell-array

How to randomly distribute data points across rows of sparse matrix


Please consider my sample code:

N=256; % some constant
data=randsrc(1,N,[1:.01:5]); % data points
b=[1,2,4,8,16] % no. of blocks where a b represents no. of rows in output matrix

How to divide data (1x256) into blocks b=[1,2,4,8,16] in a random grouping of data indices like this using a for loop:

For a single output matrix following are the conditions:

  1. Each row randomly picks the data point excluding the data points picked up by other row(s).

  2. The rest of the indices in a row have a zero.

Output matrices are as follows:

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

out2= is a 2xN matrix
      row 1 picks random 128 data points and rest of indices are zero. 
      row 2 picks rest of the 128 data points (excluding data points of row 1)
      and places them at a different index (other than that of row 1).

Similarly,

out4=  is a 4xN matrix
       Each row uniquely picks random 64 data points

out8=  is 8xN matrix
       and Each row picks 32 random data points 

out16= is a 16xN matrix
       and Each row picks 16 random data points.

How can you do this using a for loop running over b=[1,2,4,8,16]?


Solution

  • Since each output matrix has a different number of rows, it is easiest to put them in a cell array of the same length as b.

    out = cell(numel(b),1);
    

    The following loop will compute the matrix for each value in b (e.g. [1 2 4 8 16]).

    for ii=1:numel(b),
        out{ii} = zeros(b(ii),N);
        partInds = floor((randperm(N)-1)*(b(ii)/N));
        out{ii}(sub2ind([b(ii) N],partInds+1,1:N)) = data;
    end
    

    For the values b=[1 2 4 8 16] and N=256 in the question, out will look like the following:

    out = 
        [ 1x256 double]
        [ 2x256 double]
        [ 4x256 double]
        [ 8x256 double]
        [16x256 double]
    

    Note that you can verify the expected number of non-zeros in each row of matrix out{ii} with sum(out{ii}>0,2).