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
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.