Find indicies of k smallest matrix elements

I'm trying to find the indicies of smallest k matrix elements.
For example if I have
A = [10 5 2; 34 5 21; 4 6 8];
and I want to find the smallest 2 elements indicies then I want indicies 7 and 3.

 Accepted Answer

[~, indices] = sort(A(:), 'ascend');
ind = indices(1:k);

1 Comment

Ah, I forgot about the A(:) trick. This works perfectly.

Sign in to comment.

More Answers (1)

[~,idx] = mink(A,2);

3 Comments

The reason is because the OP was using older version of MATLAB, in case you were wondering.
I'm using R2020b, that's the newest isn't it?
mink gives minimums over a dimension, not the whole matrix. Sindar's code doesn't work for my example above.
Unfortunately not everyone has the Crystal Ball.

Sign in to comment.

Categories

Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!