option to stop printing the results in an output file

3 views (last 30 days)
Hi! I am working on a matlab code that contains many functions. In each mfile I inserted a fprintf to print the results in a file that I called output file. I want to run some simulations but I must insert in all the .m files an option to not print out the output in that file (else with many simulations it won't work to keep adding to the output file). What option must I add? I appreciate your fast reply!
Best regards, Alaa
  1 Comment
Jan
Jan on 4 Mar 2013
Edited: Jan on 4 Mar 2013
"Fast reply"?! We are volunteers. Any pushing is futile.

Sign in to comment.

Answers (1)

Jan
Jan on 4 Mar 2013
You can create a dedicated function for the output:
function myFprintf(varargin)
persistent FID
cmd = vargargin{1};
if strcmp(cmd, '$open') % Or what ever
FileName = varargin{2};
FID = fopen(FileName, 'w');
if FID == -1
error('Cannot open file: %s', FileName);
end
fprintf(1, '==> File opened for writing: %s\n', FileName);
return;
elseif strcmp(cmd, '$close') % Or what ever
if FID ~= 0
FileName = fopen(FID);
fprintf(1, '==> Close file: %s\n', FileName);
fclose(FID);
end
FID = 0;
return;
end
if FID ~= 0
fprintf(FID, varargin{:});
else
fprintf(1, varargin{:}); % Write to command window instead?!
end
Now a leading myFprintf('$open', fullfile(Folder, File)) opens a file an all following calls are written to this file. But myFprintf('$close') closes the file and subsequent calls avoid writing to the file.
Now you have to find and replace the existing fprintf calls to myFprintf (or a nicer name...).

Community Treasure Hunt

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

Start Hunting!