简体   繁体   中英

Matlab find indexes of x min values in column

I there any build function in Matlab which would find in column indexes of x(parameter) min values?

For example:

a = [1; 2; 3; 4; 0; 5]
someFindFunction(a, 2)
ans = [5, 1]
someFindFunction(a, 1)
ans = [5]
someFindFunction(a, 3)
ans = [5, 1, 2]

If you don't mind doing them all, then [~, ans] = sort(a) will do the trick. You can then take the first few elements of ans that you actually need. The build in sort is extremely fast and this should be performant enough despite finding all the mins and not just the ones you need.

@NirFriedman actually did answer your question, but this is an answer that is more self-contained. sort with the second output parameter tells you where each of the values appear in the original matrix after you sort them. As such, if you wanted to make what you asked into a function, you would use the second parameter to index into the second output and only produce those values from the first element up to as many as you desire. Let's also call this something else instead of someFindFunction , like findSmallestLocations . As such:

function [out] = findSmallestLocations(a, ind)
    %// Sort the values and get where they're located
    [~,b] = sort(a);

    %// Retrieve the locations that you want from 1 up to ind
    out = b(1:ind);

end

This should now produce what you want. If you want to run this on your own, copy and paste the above code into a M-file called findSmallestLocations.m , then set your current working directory to where this file is located so you can call this function.

Going with your example input and expected outputs, this is what we get:

>> a = [1; 2; 3; 4; 0; 5]
>> findSmallestLocations(a, 2)

ans =

5
1

>> findSmallestLocations(a, 1)

ans =

5    

>> findSmallestLocations(a, 3)

ans =

5
1
2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM