3D Matrix indexing from a vector

1 view (last 30 days)
Aviv Ofir
Aviv Ofir on 13 Nov 2012
Hi,
If one puts a matrix of indices I to a vector A (e.g,: A(I)) one would get an output with the size of I filled with the values of A in the location given by I. Now, suppose A is now a matrix itself, and I want the above procedure to be applied to each row of A individually, placing each output matrix in a different page of a resultant 3D array.
Here is a sample code that works using a loop:
A=[ 1 2 3 4 5 6 7 8 9 0;... % values
11 12 13 14 15 16 17 18 19 20;...
21 22 23 24 25 26 27 28 29 30;...
31 32 33 34 35 36 37 38 39 40;...
41 42 43 44 45 46 47 48 49 50];
I=[7 8 5 7 9 5 6 7 8 9;... indices
2 3 1 4 3 1 4 2 3 1];
% Build Acube
for i=1:size(A,1)
tmp=A(i,:);
Acube(:,:,i)=tmp(I);
end;
The question is: how can you vectorize it? (I note I used "large" (>=5) values for the first row of I, and "small" values (<5) for the second row to ease debugging - but any value between 1 and size(A,2) should work).

Accepted Answer

Matt J
Matt J on 13 Nov 2012
Edited: Matt J on 13 Nov 2012
[m,n]=size(I);
Acube=reshape(A(:,I).',m,n,[]),

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!