MATLAB Examples

Clean Up When Functions Complete

Contents

What to clean up

A good programming practice is to make sure that you leave your program environment in a clean state that does not interfere with any other program code. For example, you might want to

  • Close any files that you opened for import or export.
  • Restore the MATLAB path.
  • Lock or unlock memory to prevent or allow erasing MATLAB function or MEX-files.
  • Set your working folder back to its default if you have changed it.
  • Make sure global and persistent variables are in the correct state.

onCleanup

MATLAB provides the onCleanup function for this purpose. This function, when used within any program, establishes a cleanup routine for that function. When the function terminates, whether normally or in the event of an error or Ctrl+C, MATLAB automatically executes the cleanup routine.

Opening a file for write without cleaning up

First attempt to write the file incorrectly

filename = 'test.txt';
data = { 'This is a cell and cannot be written' };
try
    myUnsafeFileWriter( filename, data )
catch err
    err.message
end
ans =

Function is not defined for 'cell' inputs.

Observe that the file handle is still open and we cannot delete it

fopen('all')
delete( filename )
ans =

     []

Perform brute force cleanup

These type of functions are the equivalent of clear all, close all

fclose( 'all' )
ans =

     0

Opening a file for write with cleaning up

Write the file incorrectly

try
    mySafeFileWriter( filename, data )
catch err
    err.message
end
ans =

Function is not defined for 'cell' inputs.

Observe that the file handle is no longer open and we can delete it

fopen('all')
delete( filename )
ans =

     []