MATLAB如何写一个有2个条件的for循环,一个是“==”,另一个是“~=”?

MATLAB how to write a for loop with 2 conditions, one is "==", the other is "~="?

我正在尝试在 Simulink 中编写一个 S-Function,输入 "t" 表示时间,"LIBs" 表示进入系统的 material 量。有2个输出。 Simulink中的思路是这样的。 Simulink model concept

我想做的是,在某个时间迭代,输入 "LIBs" 转到不同的输出。但是在迭代过程中,有一些特殊的点我不希望输入到任何输出。

代码是这样的:

MATLAB

function [Batts_Spent, Batts_N_Spent] = BattsL6Y(t, LIBs)
for t = 2011:6:2035 
    if t ~= 2005:10:2035
        Batts_Spent = LIBs;
    end
end
for t = 2015:10:2035 
    if t ~= 2005:6:2035
        Batts_N_Spent = LIBs;
    end
end
for t = 2011:6:2035 
    if t == 2015:10:2035
        Batts_Spent = LIBs;
    end
end
end

我确定这段代码不正确,但我不知道如何正确编写。

而且,即使我有多个输入输出端口,Simulink工程中的S-Function模块仍然只有一个输入输出端口。我应该将其更改为 MATLAB Function 块吗?

在你的例子中,t 是一个输入参数,这使得它看起来像是为 t 的每个值调用了函数。然后你有一个循环遍历 t 的所有值。考虑到您的形象,您根本不需要循环。您可以将 ifmod 结合使用。例如:

function [Batts_Spent, Batts_N_Spent] = BattsL6Y(t, LIBs)
if mod(t-2005,6)==0 && t>=2005
  Batts_Spent = LIBs;
end
end

这只是 "Every 6th time the value of LIBs will be assigned to the first output"。这不是一个完整的解决方案,但应该足以让您入门。对于其他输出,您需要一秒钟。