Get value closest to zero from array in MatLAB?
An interesting (and probably simple) problem for you all, I have two arrays, and I need to determine the real minimum (i.e value closest to zero) and the real maximum (i.e. value furthest from zero) regardless of whether that value is positive or negative.
To do this, I have calculated the positive_max and the positive_min, as well as the negative_max and the negative_min as show开发者_如何学运维n below...
test = [3, 4, -2, -7, 6];
positive_min = min(test(test>=0)); %Should be 3
positive_max = max(test(test>=0)); %Should be 6
negative_max = min(test(test<=0)); %Should be -7
negative_min = max(test(test<=0)); %Should be -2
Trouble is, I now need to compare the positive_min to the negative_min to see which is closest to zero, as well as comparing the positive_max to the negative_max to see which is furthest from zero. I can't seem to figure out how to do this...
I would appreciate any help!
You could try using the abs
function
min(abs(test))
gives 2
and
max(abs(test))
gives 7
. If you want to find the actual signed value of each of these, you can use the second output option from min and max:
[~, inx] = min(abs(test));
test(inx)
ans =
-2
[~, inx] = max(abs(test));
test(inx)
ans =
-7
Matlab already takes the absolute value for max() or min() for complex numbers.
So another quick way to do this would be min(test+1i)-1i
or max(test+1i)-1i
精彩评论