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

Logging in a Matlab Script

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

Hello!

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.

Thanks!

0 Comments

Alexander

Products

No products are associated with this question.

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');
  end
  return;
elseif strcmp(Data, 'close')
  fclose(FID);
  FID = -1;
end
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.

3 Comments

Paulo Silva on 24 Feb 2011

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

Jan Simon on 24 Feb 2011

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).

Matthew on 14 Jan 2014

+1 nice and simple exactly what I needed.

Jan Simon

Contact us