Matlab的. if/else if/else语句中的向量化 [英] matlab. vectorization within if/else if/else statements

查看:106
本文介绍了Matlab的. if/else if/else语句中的向量化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以下代码的帮助:

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

以下是示例数据:

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

我不确定如何使代码正常工作.它只接受第一个参数,而忽略else if和else参数.请帮忙.谢谢.

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.

推荐答案

if x(:,3)>x(:,4)并不真正起作用,if期望truefalse不是向量.因此,它只计算向量x(:,3)>x(:,4)的第一个元素,这就是为什么它似乎忽略了elseif的原因.

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)

这篇关于Matlab的. if/else if/else语句中的向量化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆