matlab. vectorization within if/else if/else statements

依然范特西╮ 提交于 2019-12-19 17:45:13

问题


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.


回答1:


if x(:,3)>x(:,4) doesn't really work, if expects either true or false not a vector. So it only evaluates the first element of the vector x(:,3)>x(:,4) which is why it appears to ignore your elseif.

So you must either use a loop or even better you can use logical indexing like this:

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)



回答2:


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)));



回答3:


Here is 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);


来源:https://stackoverflow.com/questions/18741764/matlab-vectorization-within-if-else-if-else-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!