Reputation: 1989
How can I find the smallest number among three that is non zero.
I tried introducing a very small number eps = 1e-6
(my numbers are either zero or clearly larger than eps) and doing tests between min(x,eps), min(y,eps) etc. I didn't get anything. Is there a way to do that with a function?
Upvotes: 2
Views: 1333
Reputation: 1744
If the numbers are all stored in a vector x
you could do the following:
x = [1 0 2 0 3 0 4];
y = min(x(x>0));
This is based on your statement that
numbers are either zero or clearly larger than
eps
If you mean larger in magnitude and you want to accept non-zero negative values you could use:
x = [1 0 -2 0 3 0 4];
y = min(x(x~=0));
Note that this will return the most negative number when negative numbers are present, rather than the number with the smallest non-zero magnitude. To get the number with the smallest non-zero magnitude, you could use:
x = [1 0 -2 0 3 0 4];
xnonzero = x(x~=0);
[~,idx] = min(abs(xnonzero));
y = xnonzero(idx);
It doesn't seem very elegant. There is probably a more direct way.
Upvotes: 5
Reputation: 1301
numbers = [1 3 4 -2 1 0];
answer = min(numbers(numbers>0));
answer == 1
Upvotes: 4