I need some help with the following code:
if x(:,3)>x(:,4)
output=[x(:,1)-x(:,2)];
elseif x(:,3)<x(:,4)
output=[x(:,2)-x(:,1)];
else
output=NaN
end
Here is a sample data:
matrix x output
10 5 1 2 -5
10 5 2 1 5
NaN 1 1 3 NaN
I'm not sure how to make the code work. It just takes the first argument and ignores the else if and else arguments. Please help. Thank you.
Using
sign
to avoid indexing for different conditions.Or in a shorter and less readable form:
if x(:,3)>x(:,4)
doesn't really work,if
expects eithertrue
orfalse
not a vector. So it only evaluates the first element of the vectorx(:,3)>x(:,4)
which is why it appears to ignore yourelseif
.So you must either use a loop or even better you can use logical indexing like this:
Here is how you can do it: