gpt4 book ai didi

matlab - MatLab环境中的if语句

转载 作者:行者123 更新时间:2023-12-03 03:27:33 25 4
gpt4 key购买 nike

我使用以下简单代码来检查 MATLAB 中 elseif 命令的属性:

x = 10;
if x < 0
y = x;
elseif 0 <= x < 2
y = 3*x;
elseif x >= 2
y = 8*x;
end
y

由于 x >= 2,我预计结果为 80。但奇妙的事情发生了!结果是 30,而不是 80!

但是为什么呢?有任何想法吗?

更新:当我将代码(按照答案中的建议)更改为

x = 10;
if x < 0
y = x;
elseif (0 <= x) && ( x < 2 )
y = 3*x;
elseif x >= 2
y = 8*x;
end
y

我按预期得到了80。正是这种双重条件让我失望了。

最佳答案

当你写的时候

if 0 <= x < 2

你真的在写(没有意识到)

if (0 <= x) < 2

评估为

if (true) < 2

这是正确的,因为 true 的计算结果为 1

所以这就是逐行发生的事情:

x = 10;            % x is set to 10
if x < 0 % false
y = x; % not executed
elseif 0 <= x < 2 % condition is (true) < 2, thus true
y = 3*x; % y is set to 3*x, i.e. 30
elseif x >= 2 % since we already passed a condition, this is not evaluated
y = 8*x; % skipped
end % end of composite if
y % display the value of y - it should be 30

顺便说一句,当您使用标量时,您应该真正使用 && 运算符,而不是 & 运算符。例如,参见What's the difference between & and && in MATLAB?

关于matlab - MatLab环境中的if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23726471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com