Save data to file for each loop and to master file

1 view (last 30 days)
I currantly have a for loop which outputs data to three individual files (3 iterations) which for the theta value (given for each iteration) shows values of T for a given X. I am now trying to also combine these file outputs into a master file (Results) so that all the data can be viewed together but I am not having any luck with the current code I am using. The whole section of code is nested within a for loop which define the theta value for each iteration.
% print values out to a text file
textfilename=['NumOutputfortheta=' num2str(theta)];
fid = fopen(textfilename,'w');
fprintf(fid,'At t=0.5\n');
fidresult=fopen('Results','w');
for i=2:N-1
fprintf(fid,'x = %10.7f\n',x(i));
%fprintf(fid,'Tanal = %10.7f\n',Tanal(i,Nt));
fprintf(fid,'T= %10.7f\n',T(i,Nt));
%fprintf(fid,'Percentage difference = %10.5f',100*(T(i,Nt)-Tanal(i,Nt))/Tanal(i,Nt));
fprintf(fid,'\n');
fprintf(fidresult,'%f\x %f\T %f\n',x(i));
end
fclose(fid); fclose(fidresult);

Answers (1)

Image Analyst
Image Analyst on 23 Dec 2014
I don't see any code where you're opening any of the 3 previously created files for reading. You just open two files for writing. Why aren't you opening any of the 3 files for reading if you plan on combining them?
  2 Comments
Mike Scott
Mike Scott on 23 Dec 2014
I haven't included a specific opening command as this does not have to happen while the program is running, they can be opened and viewed at a later stage. In the same way I would like to include a file that combines all the data into one file.
Image Analyst
Image Analyst on 23 Dec 2014
Well I'm confused. You said you created 3 files and now want to combine the data in the 3 files into a single file. So you can do that in one of two ways
  1. Open an output file for writing, and the 3 other files for reading. Then call fgetl() to read the input files, and fprintf() to write to the output file.
  2. Or use your variables that you already have in your program to write them directly to an output file with fprintf().
I really don't know why you say you don't need to call fopen() ("a specific opening command") - how else are you going to write the file?
Another confusing statement. True, any file "can be opened and viewed at a later stage" but that doesn't have anything to do with the process of creating the files you need. Create the 3 files, then create the single combined file, then view them at whatever time you want. But you have to create them first.

Sign in to comment.

Categories

Find more on Data Import and Export in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!