[英]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.