4

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

2 Answers 2

3

Just use linear indexing:

nElementsPerSlice = numel(indexes);

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

K = J(linearIndices);
Sign up to request clarification or add additional context in comments.

Comments

1

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]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.