0
votes

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.

1
You can be sure that values of Ind is between 1-40?Adiel
Yes, that's great! But what are you expecting from SO? Please elaborate your question according to the guidelines.RC0993
@Adiel: yes, I've added this assumption.Uri Cohen
So see my answerAdiel

1 Answers

3
votes

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