Matlab vectorization inside if / else if / else

I need 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 sample data:

 matrix x output 10 5 1 2 -5 10 5 2 1 5 NaN 1 1 3 NaN 

I am not sure how to make the code work. It simply takes the first argument and ignores the else if and else arguments. Please help. Thanks.

+7
vectorization if-statement matlab
source share
3 answers

if x(:,3)>x(:,4) really does not work, if expects either true or false not a vector. Therefore, it only evaluates the first element of the vector x(:,3)>x(:,4) , so it ignores your elseif .

So, you should either use a loop, or even better, use logical indexing as follows:

 x= [10 5 1 2 10 5 2 1 NaN 1 1 3] output = NaN(size(x,1),1) I = x(:,3)>x(:,4); output(I) = x(I,1)-x(I,2); I = x(:,3)<x(:,4); output(I) = x(I,2)-x(I,1) 
+8
source share

Using sign to avoid indexing for different conditions.

 B=diff(x,1,2); B(B(:,3)==0,3) = NaN; output = B(:,1) .* sign(B(:,3)); 

Or in a shorter and less readable form:

 B=diff(x,1,2); output = B(:,1) .* (sign(B(:,3))+0./sign(B(:,3))); 
+5
source share

Here's how you can do it:

 output = NaN(size(x,1),1); idx1 = x(:,3)>x(:,4); idx2 = x(:,3)<x(:,4); output(idx1) = x(idx1,1)-x(idx1,2); output(idx2) = x(idx2,2)-x(idx2,1); 
+2
source share

All Articles