Pick x smallest elements in Matlab

2019-09-16 19:06发布

问题:

I have a matrix of integer values, the x axis represent different days and y axis represents hour of the day. And in each cell is a number that indicates how many hours of the day of the day correspond some criteria of the day which is just going on. That's why I need to calculate it for every hour and not only at the end of the time.

The whole issue is I have then to pick 5 best days which have the lowest number (least corresponding). So basically in the matrix it means select 5 lowest numbers in the row and remember the indexes of the columns where the minimum is. (I need to know in which day it occured). Because at every time as the time goes on it can be 5 different days so sorting the whole table would do mess.

I can make it work really ugly by taking first 5 number and then when if I find smaller one on the way I will forget biggest one from the 5 and remember the index of the column for the new one. Yet this solution seems to be pretty sloppy. There has to be a better way in Matlab how to solve this.

Any ideas, functions that can make my life easier?

1 1 0 1 1 1 0 0 1 1

1 2 1 2 2 1 0 1 2 2

For example in these two rows indexed from 1-10, in the first row it should return columns 3,7,8 and two others not really caring which one. In the second row it should return columns 7,8,6,1,3.

回答1:

A = randi(60,100,2);
[min_val,index] = sort(A(:,2),'ascend');    
output = [A(index(1:5),1) A(index(1:5),2)];

this should help you (I guess);



回答2:

Probably one of the simplest (but not most efficient) way is to use the sort function (which also returns sorted indices):

>> [~,index] = sort([1 1 0 1 1 1 0 0 1 1]);
>> index(1:5)
ans =

     3     7     8     1     2

>> [~,index] = sort([1 2 1 2 2 1 0 1 2 2]);
>> index(1:5)

ans =

     7     1     3     6     8