Find three largest and smallest values in column of table
4 次查看(过去 30 天)
显示 更早的评论
Hello, so I have a 1500x15 table, in which one column represents profits for that asset. I would like to know how to code to return the three largest and smallest values in column 4. Additionally, I would like the code to also return the corresponding name (in column 1) of these values.
0 个评论
回答(2 个)
Peter Perkins
2015-8-5
As Walter said, this is just sorting. In R2013b or later, use a table:
>> asset = {'a'; 'a'; 'a'; 'b'; 'b'; 'b'; 'c'; 'd'; 'e'};
>> price = rand(9,1);
>> x = randn(9,1);
>> data = table(asset,price,x)
data =
asset price x
_____ _______ _________
'a' 0.81472 2.7694
'a' 0.90579 -1.3499
'a' 0.12699 3.0349
'b' 0.91338 0.7254
'b' 0.63236 -0.063055
'b' 0.09754 0.71474
'c' 0.2785 -0.20497
'd' 0.54688 -0.12414
'e' 0.95751 1.4897
>> data = sortrows(data,'price');
>> smallest = data([1 2 3],:)
smallest =
asset price x
_____ _______ ________
'b' 0.09754 0.71474
'a' 0.12699 3.0349
'c' 0.2785 -0.20497
>> largest = data([end-2 end-1 end],:)
largest =
asset price x
_____ _______ _______
'a' 0.90579 -1.3499
'b' 0.91338 0.7254
'e' 0.95751 1.4897
0 个评论
Walter Roberson
2015-8-4
Extract the values. sort() them, also returning the index as the second output of sort(). The first three sorted values are the three smallest values. The last three sorted values are the three largest values. The corresponding entries from the second output of sort can be used to index the name column.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!