How to select 2nd largest number (or largest if no 2nd largest)

8 ビュー (過去 30 日間)
Julie
Julie 2011 年 9 月 30 日
I need to find the second largest number in a vector but the number of elements from 4 to 1 so sometimes there is no second largest number (only the largest number) and in this case I can use the largest number.
I started with b=sort(a) c=(b(:,end-1)
but obviously I get an error when there is only 1 element.
Sorry if I am missing the obvious here!
  1 件のコメント
Julie
Julie 2011 年 10 月 3 日
many thanks, it worked beautifully, esp using 'unique' for those pesky duplcates values!

サインインしてコメントする。

採用された回答

Matt Tearle
Matt Tearle 2011 年 9 月 30 日
Is it possible to have repeated values? If so, what do you define as the "second largest" value? Eg secondmax([1 2 3 3]) = 2? or 3?
y = [x(1),unique(x)];
z = y(end-1);
gives the first option. Replacing unique with sort gives the second.

その他の回答 (2 件)

Wayne King
Wayne King 2011 年 9 月 30 日
Hi Julie, one simple way is
N = 1;
x = randn(N,1);
b = sort(x,'descend');
if (length(b)>1)
b(2)
else
b(1)
end
  1 件のコメント
Wayne King
Wayne King 2011 年 9 月 30 日
Obviously, you can change N above to something greater than 1, e.g. N = 4

サインインしてコメントする。


Jan
Jan 2011 年 9 月 30 日
There are some methods:
b = sort(a);
c = b(max(1, end-1));
Or:
b = sort(a, 'descending');
c = b(max(2, length(b)));
Or:
if length(a) == 1
c = a;
else
b = sort(a, 'descending');
c = b(2);
end

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by