Fix an undefined variable in a nested if function?

So here's a part of my code:
if ((destination_one > 0)&&(location_caller > 0))||((destination_one < 0)&&(location_caller < 0))
dc1 = abs(destination_one - location_caller);
elseif ((destination_one > 0)&&(location_caller < 0))||((destination_one < 0)&&(location_caller > 0))
dc1 = (abs(destination_one) + abs(location_caller));
end
if ((destination_two > 0)&&(location_caller > 0))||((destination_two < 0)&&(location_caller < 0))
dc2 = abs(destination_two - location_caller);
elseif ((destination_two > 0)&&(location_caller < 0))||((destination_two < 0)&&(location_caller > 0))
dc2 = (abs(destination_two) + abs(location_caller));
end
condition_4 = [(dc2 > dc1), (dc2 < dc1)];
check_condition_4 = sum(condition_4);
Whenever I try to run it against certain test cases, it will return an error saying that, for condition_4, dc2 is undefined. Is my end statement placement wrong? Thanks in advance.

 Accepted Answer

In the first group, neither branch is true if either value is 0 exactly. There are probably also failures if one of the values is NaN.
If you have an if/elseif that defines variables then you should always prepare for the possibility that neither branch is true and make sure the variable is defined anyhow.
If you are sure that the elseif is testing the exact opposite of the if, then why bother to elseif? Why not just if/else ?
Your first test is equivalent to
(destination_one ~= 0) && (location_one ~=0) && sign(destination_one) == sign(location_one)
and the elseif is equivalent to
(destination_one ~= 0) && (location_one ~=0) && sign(destination_one) ~= sign(location_one)
(except perhaps in what happens if a value is NaN)

More Answers (0)

Categories

Find more on Debugging and Improving Code in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!