MATLAB: How to put selected rows of a matrix into a cell in order defined by another matrix’s elements

matrix elements to cell

Let's say we have matrix A 50 by 50. and we have matrix B=[10 14 17 20 25] how can I put the rows of A(B(i)) into a cell. So if S is a cell S{1}=A(10,:), S{2}=A(14,:) … S{5}=A(25,:) this is just an example the numbers are made up. I tried this which didnt work. Many thanks.
n=numel(A);
for i=1:n
for jj=1:n
S{jj}=(A(:,B(i)));
end
end

Best Answer

Don't fight MATLAB with nested loops, this is such a slow way to code (especially without cell array preallocation). Learn to use MATLAB efficient indexing and inbuilt functions (such as num2cell):
>> A = rand(50);
>> B = [10,14,17,20,25];
>> C = num2cell(A(B,:),2)
C =
[1x50 double]
[1x50 double]
[1x50 double]
[1x50 double]
[1x50 double]