[英]Matlab not solving if statements
I'm having a bit of trouble iterating through a few if
statements more than eight times. 我在遍历几次if
语句超过八次时遇到了麻烦。 The code seems to work fine for the first several comparisons, performs the arithmetic and return/saves the output row 'export_data'
. 该代码对于前几次比较似乎工作正常,执行算术并返回/保存输出行'export_data'
。 However, after that, it only returns the else
condition and response. 但是,此后,它仅返回else
条件和响应。 The variables beings assessed have 1500 rows each. 评估的变量各有1500行。 I've added the code below and two photos showing the outputs. 我添加了以下代码和两张显示输出的照片。 Any insight will be very much appreciated. 任何见解将不胜感激。
function [export_data] = WS_Zones(Forecast_WS, Observed_WS)
if (Forecast_WS > Observed_WS)
WS_Zone_1 = Observed_WS.*1.24;
WS_Zone_2 = Observed_WS.*1.28;
elseif (Forecast_WS < Observed_WS)
WS_Zone_1 = Observed_WS.*0.76;
WS_Zone_2 = Observed_WS.*0.72;
else
WS_Zone_1 = Observed_WS;
WS_Zone_2 = Observed_WS;
end
export_data=[Forecast_WS Observed_WS WS_Zone_1 WS_Zone_2];
filename = 'testdata.xlsx';
sheet = 1;
xlRange = 'A1';
xlswrite(filename,export_data,sheet,xlRange)
end
This statement: 这个说法:
if [1 2 3] > [1 1 1]
disp('hello');
end
will never print "hello" even though 2
and 3
are both greater than 1
. 即使2
和3
都大于1
也永远不会打印“ hello”。 This is because the if
statement needs to evaluate to either scalar true
or false
. 这是因为if
语句需要评估为标量true
或false
。 If a vector is used, than only the first element is used to determine if the statement is true or not (comparisons between other elements are ignored). 如果使用向量,则仅使用第一个元素来确定该语句是否为真(其他元素之间的比较将被忽略)。 You can use any
and all
if you want to apply conditions on all elements. 如果要对所有元素应用条件,则可以使用any
和all
。
If Forecast_WS
and Observed_WS
aren't scalars then you need to wrap your if
statement in a for
loop, eg: 如果Forecast_WS
和Observed_WS
不是标量,则需要将if
语句包装在for
循环中,例如:
WS_Zone_1 = Observed_WS;
WS_Zone_2 = Observed_WS;
for i = 1:numel(Forecast_WS)
if Forecast_WS(i) > Observed_WS(i)
WS_Zone_1(i) = Observed_WS(i).*1.24;
WS_Zone_2(i) = Observed_WS(i).*1.28;
elseif Forecast_WS(i) < Observed_WS(i)
WS_Zone_1(i) = Observed_WS(i).*0.76;
WS_Zone_2(i) = Observed_WS(i).*0.72;
end
end
or vectorize it using logical indexing : 或使用逻辑索引对其向量化:
WS_Zone_1 = Observed_WS;
WS_Zone_2 = Observed_WS;
idx = (Forecast_WS > Observed_WS);
WS_Zone_1(idx) = Observed_WS(idx).*1.24;
WS_Zone_2(idx) = Observed_WS(idx).*1.28;
idx = (Forecast_WS < Observed_WS);
WS_Zone_1(idx) = Observed_WS(idx).*0.76;
WS_Zone_2(idx) = Observed_WS(idx).*0.72;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.