Find three largest and smallest values in column of table

조회 수: 3 (최근 30일)
xander fong
xander fong 2015년 8월 4일
답변: Peter Perkins 2015년 8월 5일
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.

답변 (2개)

Peter Perkins
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

Walter Roberson
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.

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by