Compare two inputs based on closeness in value to a variable?

Hi everyone,
I'm trying to write a statement that compares two inputs to a number. Depending on which of them is closer to that number, a statement will use the closer variable that in a calculation.
So for example, I have two inputs from a GUI.
x = 44, and y = 52
Whichever one is closer to 51 will be used in an equation (i.e. y)
Does anyone know how I can accomplish this?
Thank you!

댓글 수: 4

I'm not sure why I didn't think of this earlier, but if anyone is interested, here's what I did.
if abs(x - 51) > abs(y - 51)
z = y;
elseif abs(x - 51) < abs(y - 51)
z = x;
end
z is then used later, so this ended up working out fine
If both x and y are equidistant from 51 then some error may rise:
if true
if abs(x - 51) > abs(y - 51)
z = y;
else
z = x;
end
end
What about solving the equal distance ambiguity with for instance
if abs(x - 51) > abs(y - 51)
z = y;
else
z=x
end
if abs(x - 51) == abs(y - 51)
z = [x y];
end
Thanks for your feedback! You're absolutely right, but this is actually being used in a GUI where I prevent x and y from being equal to each other with error messages and a break statement.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

질문:

2017년 8월 14일

댓글:

2017년 8월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by