1

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
Ran
  • 4,117
  • 4
  • 44
  • 70
  • are the size numbers in the `data` and `idx` matrices really their dimensions? if so why are they different and what's the meaning of the 1s? – McMa Feb 24 '14 at 11:54
  • 1
    Just a general comment: it is best [not to use `i` and `j` as variable names in Matlab](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab). – Shai Feb 24 '14 at 12:00

2 Answers2

1

I think using reshape can help here

tmp = reshape( data, size(data,1), [] );
d = tmp( sub2ind( size(tmp) ), idx(:), 1:size(tmp,2) );
Shai
  • 111,146
  • 38
  • 238
  • 371
1
[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);
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147