Returning Incorrect index of array

14 views (last 30 days)
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 =
index =
Please help to solve. TQVM
Khairul Nur
Khairul Nur on 22 Jul 2021
tq stephen for the code, really appreciate that!

Sign in to comment.

Accepted Answer

Bjorn Gustavsson
Bjorn Gustavsson on 9 Jul 2021
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.

Sign in to comment.

More Answers (1)

Viranch Patel
Viranch Patel on 9 Jul 2021
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:)
Khairul Nur
Khairul Nur on 12 Jul 2021
tq viranch.. great! its working

Sign in to comment.


Community Treasure Hunt

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

Start Hunting!