minimun value in a column matrix with its index

1 回表示 (過去 30 日間)
kurdistan mohsin
kurdistan mohsin 2022 年 6 月 10 日
コメント済み: Voss 2022 年 6 月 10 日
hi, I write the bellow code to find the minimum value in a column vector but it should not consider zero as a minimum , but how to find the exact indexing of the minimum value?
in the example the row index of minimum value exept zero should be 2 , why it give me 1?
can anybody correct it for me so the row_idx = 2 !
A=[0; 5 ;6 ;9 ;55]
A = 5×1
0 5 6 9 55
[min_value,row_idx]=min(A(A~=0))
min_value = 5
row_idx = 1

採用された回答

Dyuman Joshi
Dyuman Joshi 2022 年 6 月 10 日
編集済み: Dyuman Joshi 2022 年 6 月 10 日
A=[0; 5 ;6 ;9 ;55]
A = 5×1
0 5 6 9 55
A(A~=0) %when you do this, your vector changes
ans = 4×1
5 6 9 55
Method 1
minvalue=min(A(A~=0))
minvalue = 5
rowidx=find(A==minvalue)
rowidx = 2
Method 2
A(A==0)=nan
A = 5×1
NaN 5 6 9 55
[min_value, row_idx]=min(A)
min_value = 5
row_idx = 2
  1 件のコメント
kurdistan mohsin
kurdistan mohsin 2022 年 6 月 10 日
thank you so much !

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

その他の回答 (1 件)

Voss
Voss 2022 年 6 月 10 日
A(A~=0) is a 4-by-1 vector:
A=[0; 5 ;6 ;9 ;55];
A(A~=0)
ans = 4×1
5 6 9 55
When you do min on that you find that 5 is the minimum, which occurs at index 1, as you can see right there.
To get the correct index in A (not in A(A~=0)) of the non-zero minimum, you can store the indices of the non-zero elements of A:
nz_idx = find(A~=0)
nz_idx = 4×1
2 3 4 5
then use min:
[min_value,temp_idx] = min(A(nz_idx))
min_value = 5
temp_idx = 1
and then get the index in A:
row_idx = nz_idx(temp_idx)
row_idx = 2
  2 件のコメント
kurdistan mohsin
kurdistan mohsin 2022 年 6 月 10 日
thanks alot!
Voss
Voss 2022 年 6 月 10 日
You're welcome!

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by