adrelino
adrelino

Reputation: 160

Indexing multidimensional array with a matrix in Matlab

How can I index the dimensions of a nd-array element-wise by using a 2d matrix which entries represent which dimensions (representing slices or 2d Matrices) to take the values from?

I=ones(2)*2;
J=cat(3,I,I*2,I*3);

indexes = [1 3 ; 2 2] ;

so J is

J(:,:,1) =

 2     2
 2     2


J(:,:,2) =

 4     4
 4     4


J(:,:,3) =

 6     6
 6     6

it works easily using 2 for loops

for i=1:size(indexes,1)
     for j=1:size(indexes,2)
        K(i,j)=J(i,j,indexes(i,j));
    end
end

which yields the desired result

K =

 2     6
 4     4

but is there a vectorized / smart indexing way of doing this?

%K=J(:,:,indexes)  --does not work

Upvotes: 4

Views: 4071

Answers (2)

wanjolivet
wanjolivet

Reputation: 91

you can use sub2ind to convert matrix indexes into linear index

ind = sub2ind( size(J), [1 1 2 2], [1 2 1 2], [1 3 2 2]);
K = resize(J(ind), [2 2]);

Upvotes: 1

Jonas
Jonas

Reputation: 74930

Just use linear indexing:

nElementsPerSlice = numel(indexes);

linearIndices = (1:nElementsPerSlice) + (indexes(:)-1) * nElementsPerSlice;

K = J(linearIndices);

Upvotes: 3

Related Questions