MATLAB Answers


Logging in a Matlab Script

Asked by Alexander on 23 Feb 2011
Latest activity Commented on by Matthew
on 14 Jan 2014


I have an m-script which starts by opening a file handle to a log file. As the script executes, messages are dumped into this textfile so I have a record of the execution and what happened. That works well enough.

Now I have added some functions and objects into by script. I would like to be able to write log messages to this same file while inside the methods of these other code segments.

I do not want to pass and return the file handle on each and every method/function call. The first thing I tried was using a global modifier to allow the filehandle to persist into these other code segments but it seems that even global objects do not exist in the workspace when an object method is called. I would like to avoid printing to the command window (and using DAIRY to save) as I like to keep that "clean" for easy input.

Any ideas? I guess what I'm looking for is either a built-in ability to record data from many locations to one file or a way to have one static object's scope/visibility to be everything.



Log in to comment.

1 Answer

Answer by Jan Simon
on 24 Feb 2011

You can create a simple function, which acts as file handler:

function WriteLog(Data)
persistent FID
% Open the file
if strcmp(Data, 'open')
  FID = fopen(fullfile(tempdir, 'LogFile.txt'), 'w');
  if FID < 0
     error('Cannot open file');
elseif strcmp(Data, 'close')
  FID = -1;
fprintf(FID, '%s\n', Data);
% Write to the screen at the same time:
% fprintf('%s\n', Data);

Now you can open and close the logging from the main function and use in in all other functions.


nice function, 1 vote for you, I'm saving it :)

I'm using a fatter version, which allows to toggle the screen output, use several output files, exclude an output file temporarily, accept cell string input, check for files closed externally by FCLOSE('all') and print warnings in red using FPRINTF(2).

+1 nice and simple exactly what I needed.

Log in to comment.

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!