0

In matlab, I commonly have a data matrix of size NxMxLxK which I wish to index along specific dimension (e.g. the forth) using an indices matrix of size NxMxL with values 1..K (assume the are all in this range):

>>> size(Data)
ans =
     7    22    128    40
>>> size(Ind)
ans =
     7    22    128

I would like to have code without loops which achieve the following effect:

Result(i,j,k) = Data(i,j,k,Ind(i,j,k))

for all values of i,j,k in range.

4
  • 1
    You can be sure that values of Ind is between 1-40? Commented Feb 4, 2019 at 8:43
  • 1
    Yes, that's great! But what are you expecting from SO? Please elaborate your question according to the guidelines. Commented Feb 4, 2019 at 8:44
  • @Adiel: yes, I've added this assumption. Commented Feb 5, 2019 at 10:19
  • So see my answer Commented Feb 6, 2019 at 12:40

1 Answer 1

3

You can vectorize your matrices and use sub2ind :

% create indices that running on all of the options for the first three dimensions:
A = kron([1:7],ones(1,22*128));
B = repmat(kron([1:22],ones(1,128)),1,7);
C = repmat([1:128],1,7*22);

Result_vec = Data(sub2ind(size(Data),A,B,C,Ind(:)'));
Result = reshape(Result_vec,7,22,128);
Sign up to request clarification or add additional context in comments.

3 Comments

This is specifically for 4-D matrix, am I correct that for a 3-D matrix the solution would have been even simpler, using [A,B]=meshgrid(...)?
Sounds like it is.
anyway, some vectors from the output matrices.

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.