Finding second smallest element in a row.

260 ビュー (過去 30 日間)
Ananya Malik
Ananya Malik 2016 年 8 月 29 日
コメント済み: Azzi Abdelmalek 2016 年 8 月 29 日
I have a row
X = [441 137 594 507 417 581 312 362 263 151 472 512 129 70 298 255 442 574 289 157 0];
I want to find the second smallest (non zero) element from X along with the column number.

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 8 月 29 日
編集済み: Azzi Abdelmalek 2016 年 8 月 29 日
X = [441 137 594 507 417 581 312 362 263 151 472 512 129 70 298 255 442 574 289 157 0];
out=min(setdiff(X,min(X)))
or
M=sort(X)
out=M(2)
  2 件のコメント
Ananya Malik
Ananya Malik 2016 年 8 月 29 日
I also wand the index of the element. i.e the column of occurrence.
Azzi Abdelmalek
Azzi Abdelmalek 2016 年 8 月 29 日
X = [441 137 594 507 417 581 312 362 263 151 472 512 129 70 298 255 442 574 289 157 0];
[out,idx]=sort(X)
val=out(2)
index=idx(2)

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

その他の回答 (1 件)

Guillaume
Guillaume 2016 年 8 月 29 日
If by 2nd smallest you mean 2nd smallest distinct value:
A = [1 0 1 2 1 4 2 3];
uA = unique(nonzeros(A)); %does sorting and remove duplicates
small2distinct = uA(2)
If by 2nd smallest you do mean 2nd smallest, so if the minimum is repeated twice, you do want the minimum:
A = [1 0 1 2 1 4 2 3];
sA = sort(nonzeros(A)); %then use plain sort
small2 = sA(2)
So, nonzeros to get all the non zero values, then sort or unique to sort the values, then take the 2nd one.

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by