gpt4 book ai didi

matlab. if/else if/else 语句中的矢量化

转载 作者:太空宇宙 更新时间:2023-11-03 19:26:40 32 4
gpt4 key购买 nike

我需要一些关于以下代码的帮助:

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 参数。请帮忙。谢谢。

最佳答案

if x(:,3)>x(:,4) 没有真正起作用,if 期望 truefalse 不是向量。所以它只计算向量 x(:,3)>x(:,4) 的第一个元素,这就是为什么它似乎忽略了你的 elseif

所以你必须使用循环或者更好的是你可以使用这样的逻辑索引:

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 语句中的矢量化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18741764/

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