Ran
Ran

Reputation: 4157

Matlab n-d indexes

I have a data matrix of size [4 1 10 128] and I have an indexes matrix of size [1 1 10 128].

Each element in the indexes matrix is a number in the range 1 to 4 that indicates which element was selected in the first dimension of the data matrix.

Now I would like to create a matrix of the selected elements, something like d = data(idx).

This doesn't work, I think because matlab is expecting linear indexes?

Any other way to do it without a loop? Thanks.

loop solution:

for i=1:size(idx,3)
  for j=1:size(idx,4)
    ind = idx(1,1,i,j);
    d(1, 1, i, j) = data(ind, 1, i, j);
  end
end

Upvotes: 1

Views: 67

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

[ii jj] = ndgrid(1:size(idx,3),1:size(idx,4));
d = data(sub2ind(size(data), squeeze(idx), ones(size(idx,3), size(idx,4)), ii, jj));
d = shiftdim(d, -2);

Upvotes: 1

Shai
Shai

Reputation: 114786

I think using reshape can help here

tmp = reshape( data, size(data,1), [] );
d = tmp( sub2ind( size(tmp) ), idx(:), 1:size(tmp,2) );

Upvotes: 1

Related Questions