필터 지우기
필터 지우기

How to find the Nth largest value in array? Even with duplicate values?

조회 수: 29 (최근 30일)
JARED VAHRENBERG
JARED VAHRENBERG 2020년 11월 6일
댓글: Image Analyst 2020년 11월 6일
If i wanted to know what the the 2nd, 3rd, 4th whatever largest value was in my array, how would i do that? I thought at first just sort the array and then get the array(N) value but if you have duplicates it doesnt work like that.
  댓글 수: 2
Ameer Hamza
Ameer Hamza 2020년 11월 6일
How do you want to handle the duplicates?
JARED VAHRENBERG
JARED VAHRENBERG 2020년 11월 6일
I just need the value itself. Like if it spit out [33]

댓글을 달려면 로그인하십시오.

답변 (1개)

Image Analyst
Image Analyst 2020년 11월 6일
Why doesn't it work? Works for me.
v = [1,2,3,4,5,5,5,5,44,55,123,456]
% Sort array in decreasing order.
sorted_v = sort(v, 'descend')
% Take the 7'th largest one. Should be 5:
N = 7;
result = sorted_v(N)
It shows
v =
1 2 3 4 5 5 5 5 44 55 123 456
sorted_v =
456 123 55 44 5 5 5 5 4 3 2 1
result =
5
If it doesn't work for you, give your vector and N and the desired output.
  댓글 수: 2
madhan ravi
madhan ravi 2020년 11월 6일
I guess probably OP wants:
v = [1,2,3,4,5,5,5,5,44,55,123,456]
v = 1×12
1 2 3 4 5 5 5 5 44 55 123 456
% Sort array in decreasing order.
sorted_v = sort(unique(v), 'descend')
sorted_v = 1×9
456 123 55 44 5 4 3 2 1
% Take the 7'th largest one.
N = 7;
result = sorted_v(N)
result = 3
Image Analyst
Image Analyst 2020년 11월 6일
Yes, I thought of that. But that's not the Nth largest value. It's the Nth largest of the unique values, which in this case (N=7) is the 10th largest value, not the 7th. But since he blew past the posting guidelines and posted it without an example, you may be right. He only said the desired output was 33 but didn't give the original vector. He only said that it "doesn't work" which might mean any number of things from a syntax error to not giving the desired values. Well, we've now given it both ways so hopefully one of those will work for Jared.

댓글을 달려면 로그인하십시오.

카테고리

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