[英]Executing all cases one after another inside a for loop in octave
到现在为止,我改变req
手动。 该代码有效,包括将结果保存到文件中。 但是现在我想为req的所有可能值运行代码。
在不将其保存到文件中的情况下,代码可以工作,但是很明显它会覆盖结果。 这就是为什么我放那行代码,根据req
的值给它起一个不同的名称来保存结果的原因。 但这给了我错误。
错误:
error: sprintf: wrong type argument 'cell' error: called from testforloop at line 26 column 1
我的代码:
clear all;
clc;
for req = {"del_1", "del_2", "del_3"}
request = req;
if (strcmp(request, "del_1"))
tarr = 11;
# and a bunch of other variables
elseif (strcmp(request, "del_2"))
tarr = 22;
# and a bunch of other variables
elseif (strcmp(request, "del_3"))
tarr = 33;
# and a bunch of other variables
else
# do nothing
endif
#long calculation producing many variable including aa, bb, cc.
aa = 2 * tarr;
bb = 3 * tarr;
cc = 4 * tarr;
#collecting variables of interest: aa, bb, cc and save it to a file.
result_matrix = [aa bb cc];
dlmwrite (sprintf('file_result_%s.csv', request), result_matrix);
endfor
如果我使用["del_1" "del_2" "del_3"]
,则错误为
error: 'tarr' undefined near line 20 column 10
error: called from
testforloop at line 20 column 4
循环内
for req = {"del_1", "del_2", "del_3"}
req
作为单元数组的每个单元而不是单元内容的值作为值(奇怪的设计决策,IMO,但这是它的工作方式)。 因此,在第一次迭代中, req={"del_1"}
。 然后可以使用req{1}
获得字符串本身。 因此,您需要更改的只是:
request = req{1};
但是,我将以不同的方式实现此目标,如下所示:
function myfunction(request, tarr)
% long calculation producing many variable including aa, bb, cc.
aa = 2 * tarr;
bb = 3 * tarr;
cc = 4 * tarr;
% collecting variables of interest: aa, bb, cc and save it to a file.
result_matrix = [aa bb cc];
dlmwrite (sprintf('file_result_%s.csv', request), result_matrix);
end
myfunction("del_1", 11)
myfunction("del_2", 22)
myfunction("del_3", 33)
我认为这样可以使您更清楚地了解自己的实际工作,而代码则不那么复杂。
请注意,在Octave中, ["del_1" "del_2" "del_3"]
计算结果为"del_1del_2del_3"
。 也就是说,您将字符串连接起来。 在MATLAB中不是这种情况,但是Octave不知道string
类型,并以与'
相同的方式使用"
创建char
数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.