Clear Filters
Clear Filters

Writing data in file and naming file with a string value

4 views (last 30 days)
Hi..
My simulations are finding errors for 4 cases in a loop as shown below. I am writing those errors in data file.
Problem is naming of the file. I want to name my files as error_200.txt, error_400.txt, error_800.txt and error_1600.txt respectively for each case. For that i have to mention the 'n' which contains different values in each loop, in the file name.
something like :fileID = fopen('error_'n'.txt','a') so that file will be automatically generated with the value of n in the name. Here is the code.............
for i = 1:4,
k = 2^i ;
n = k*100
for step = 1:1000
% here some calculations happen and data is generated,
% and i write those date (error) in a file.
error = n % for example
D = [step; error;];
fileID = fopen('error_'n'.txt','a');
fprintf(fileID,'%6.2f %12.4f\n',D);
fclose(fileID);
end
end
Currently it writes all the data in single file. Pl help me modify the code to include the value of 'n' filename while writing the data so that 4 different file are generated with different names.
Thanks.

Accepted Answer

Yoav Livneh
Yoav Livneh on 18 Feb 2015
Change your fopen line to:
fileID = fopen(['error_', num2str(n), '.txt'],'a');
  4 Comments
Yoav Livneh
Yoav Livneh on 18 Feb 2015
Just use
figure(n);
plot(step,error);
or just
figure;
plot(step,error);
The first option will always use the same four figures and overwrite the previous plots, the second option will always create new figures.

Sign in to comment.

More Answers (0)

Categories

Find more on Interactive Control and Callbacks 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!