hi,
The simple code below try to find the min value and its index, excluding 0
x = [0 0.5 4 5];
[r,index] = min(x(x>0))
The min value is correctly founded as 0.5. However, why the index returns as 1, it suppose to return 2
r =
0.5000
index =
1
Please help to solve. TQVM

2 件のコメント

Stephen23
Stephen23 2021 年 7 月 12 日
Without changing any data values:
x = [0,0.5,4,5];
idx = find(x);
[val,idy] = min(x(idx));
val
val = 0.5000
idx(idy)
ans = 2
Khairul Nur
Khairul Nur 2021 年 7 月 22 日
tq stephen for the code, really appreciate that!

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

 採用された回答

Bjorn Gustavsson
Bjorn Gustavsson 2021 年 7 月 9 日

0 投票

It returns 1 for the index because the way you call min, x(x>0) becomes the array [0.5 4 5], and the first element of that array is the smallest.
HTH

3 件のコメント

Khairul Nur
Khairul Nur 2021 年 7 月 9 日
understood, there is any way still excluding the zero but to get the index as 2?
Scott MacKenzie
Scott MacKenzie 2021 年 7 月 9 日
I'm not sure if there's a one-liner, but this will work:
x = [0 0.5 4 5];
x(x==0) = realmax;
[~, idx] = min(x)
idx = 2
Khairul Nur
Khairul Nur 2021 年 7 月 12 日
tq scott ur the best!

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

その他の回答 (1 件)

Viranch Patel
Viranch Patel 2021 年 7 月 9 日

1 投票

So if you write y = x(x>0), then it will take value only which is greater than 0 from the x and put it into y.
x = [0 0.5 4 5];
y = x(x>0);
[r,index] = min(x(x>0));
So y will be equal to [0.5000 4.0000 5.0000].
Now if you find minimum then the index will be 1 not 2.
I hope you get the answer:)

3 件のコメント

Khairul Nur
Khairul Nur 2021 年 7 月 9 日
understood, there is any way still excluding the zero but to get the index as 2?
Viranch Patel
Viranch Patel 2021 年 7 月 9 日
If I'm guessing correct, you want to get the index of the lowest positive value. Then you can do this using a single for loop in which you can have two variables, one will store the minimum value and one will store the index.
index = 0;
x = [0 0.5 4 5];
min_value = max(x);
len = length(x);
for i = 1:len
if x(i) < min_value && x(i) > 0
min_value = x(i);
index = i;
end
end
This is quite straight-forward. So you can edit this according to your need.
Khairul Nur
Khairul Nur 2021 年 7 月 12 日
tq viranch.. great! its working

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

カテゴリ

ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by