MATLAB : using fprintf in a loop
Posted on 2004-10-06
GOAL: I want to write a loop so that a text file is generated using data that has been stored in a series of systematically named MAT files.
The loop code is here:
openfile = strcat('CEA_costlevel',lev,'.txt');
out1 = fopen(openfile,'w')
createdate = datestr(now);
for run = 1:runs
runstr = int2str(run_num);
printstring = strcat('nh_run =',runstr,'\tDate =',createdate,'\n');
for strat_num = 1:strategies
strat = int2str(strat_num);
printstring = strcat('strat\tdis_cost\n');
%PROBLEM IS: HOW TO GENERALIZE THE LINE BELOW?
fprintf(out1,''%d\t%10.4f\n', strat_num, run_1strat_1.tot_dis_cost);
The problem is with the "fprintf" line. the variable names for the float variables are systematically named as follows. run_1strat_1.tot_dis_cost should be printed to the file in the first iteration of the loop, then run_1strat_2.tot_dis_cost in the next iteration, and run1strat_3.tot_dis_cost in the next, and so on till the inner and outer loop are exhausted.
In the other situations where I need to fprintf something, a made a string "printstring" first. But I can't figure out to make the printstring when there are formated float variables that need to be part of the string. I thought typing \' would let me insert a single quote but this doesnt work in MATLAB.
Thanks to anyone who can help me with this.