How to use indexes returned from min function in matlab?

How can I use the indexes returned from the min function in matlab to get the data in the 3D matrix of the third dimension? For example, I have the code below:

%a is a 3D matrix
[res, index] = min(a, [], 3);

I want to access the min elements using an index, for example:

a(index);

NOTE. I do not want to use the res variable

+3
source share
1 answer

to get them all:

a=rand(3,2,3);
[res, index] = min(a, [], 3);

sizeA=size(a);
sizeA12 = prod(sizeA(1:2));
lin_idx = sub2ind([sizeA12 sizeA(3)],1:sizeA12,index(:)');
a(lin_idx)

ans =

        0.0344   0.0971   0.171   0.695  0.0318  0.187

>> res(:)'

ans =

        0.0344   0.0971   0.171   0.695  0.0318  0.187

More general approach

a=rand(3,2,3); % sample data

dim_min = 2; % dimension along to take the minimum
[res, index] = min(a, [], dim_min);

sizeA       = size(a);
sizeAstart  = prod(sizeA(1:dim_min-1));
sizeAend    = prod(sizeA(dim_min+1:end));
idstart     = repmat(1:sizeAstart,1,sizeAend);
idend       = repmat(1:sizeAend  ,1,sizeAstart);

lin_idx = sub2ind([sizeAstart sizeA(dim_min) sizeAend ],idstart,index(:)',idend);
a(lin_idx)

You can also modify the result to get it in the same sizes as the original matrix (with no minimized size):

reshape(a(lin_idx),sizeA([1:dim_min-1 dim_min+1:end]))

Works for any size data matrix or any value dim_min(for now 1<=dim_min<=ndims(a), of course)

+3
source

All Articles