到现在为止,我手动更改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
得到的值中的每个单元阵列的细胞,而不是单元格的内容(怪异的设计决策,海事组织,但这是它的工作方式)。因此,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)
我想,这得到的你实际上在做什么更清晰的视野,降低了代码的复杂。
需要注意的是在八度,["del_1" "del_2" "del_3"]
评估为"del_1del_2del_3"
。也就是说,你在连接字符串。在MATLAB这种情况并非如此,但倍频不知道string
类型,并使用"
以同样的方式作为'
创建char
阵列。