Alastair_V
Alastair_V

Reputation: 45

Storing vectors into a cell array

I have a 128x100 matrix called R.

I have another 1x100 matrix called I. Values in vector I range from 1-64.

e.g. I: [13,22,55,63 ... ,35]

There is a one-to-one correspondence between elements of R and I.

I want to know for each unique value of I, i.e. if 1 occurs in six positions (column# 12, 20, 35, 62, 87, 95) in vector I, how to concatenate the corresponding (column# 12, 20, 35, 62, 87, 95) columns in R and store the info in a single cell array S for all such values from 1-64.

I tried but am not able to think of a compact and correct code.

for j = 1:64
   for i = 1:100
       if I(i) == j
           S{j} = R(:,i);
       end      
   end    
end

Upvotes: 2

Views: 396

Answers (2)

rahnema1
rahnema1

Reputation: 15837

A solution using accumarray:

S = accumarray(I(:),1:100,[64 1],@(x){R(:,x)});

If array I doesn't contain all values of 1:64 S will have empty cells that can be removed this way:

S(cellfun(@isempty,S))=[];

*Thanks to @LuisMendo for suggestion to improve the answer.

Upvotes: 4

Luis Mendo
Luis Mendo

Reputation: 112659

This does what tou want:

S = arrayfun(@(n) R(:,I==n), 1:64, 'UniformOutput', false);

Or, with an equivalent loop:

S = cell(1,64);
for n = 1:64
  S{n} = R(:,I==n);
end

Upvotes: 1

Related Questions