简体   繁体   中英

Executing all cases one after another inside a for loop in octave

Until now, I change req manually. The code works, including saving the result into a file. But now I want to run the code for all possible values of req.

Without saving it into a file, the code works but obviously it overwrite the result. That is why I put that line of code that saving the result by giving it a different name depending of the values of req . But this gives me error.

error:

 error: sprintf: wrong type argument 'cell' error: called from testforloop at line 26 column 1 

my code:

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

if I use ["del_1" "del_2" "del_3"] , the error is

error: 'tarr' undefined near line 20 column 10
error: called from
    testforloop at line 20 column 4

Inside the loop

for req = {"del_1", "del_2", "del_3"}

req gets as value each of the cells of the cell array, not the contents of the cells (weird design decision, IMO, but this is the way it works). Thus, req={"del_1"} in the first iteration. The string itself can then be obtained with req{1} . So all you need to change is:

request = req{1};

However, I would implement this differently, as so:

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)

I think this obtains a clearer view of what you're actually doing, the code is less complicated.


Note that in Octave, ["del_1" "del_2" "del_3"] evaluates to "del_1del_2del_3" . That is, you concatenate the strings. In MATLAB this is not the case, but Octave doesn't know the string type, and uses " in the same way as ' to create char arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM