How to Execute a Command Automatically When MATLAB Quits

MATLAB provides a mechanism to execute automatically a set of commands before it quits.


MATLAB tries to execute a script file called ‘finish.m’ before it quits. This file must be in the search path, and if multiple coincidences are found, only the first file is executed.

To execute a command automatically when MATLAB is terminating:

  1. Execute the code edit 'finish.m' to open the file in the Editor
  2. Add the command to the file
  3. Save the file and verify that it is in the search path

Note: If a file called ‘finish.m’ does not exist, MATLAB will ask to create it. Accept and verify that the file is saved to a location in the search path.


Add to the ‘finish.m’ file the commands that you repetitively execute at the end of each work session with MATLAB. For example:

  1. Save all variables in the workspace to a .MAT file
  2. Delete temporary files

Further reading

I recommend the following books to learn more on the MATLAB environment.

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a 2017 Textbook Excellence Award. The first chapter explains the windows of the MATLAB environment, among other introductory topics like operators, random numbers, and trigonometry.

  2. MATLAB for Engineers (5th Edition)

    This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. The second chapter explains the windows of the MATLAB environment, how to name variables, and how to save a series of commands in an .M file, among other topics.

I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.

doc finish;

Source code

I hope you have learned what the ‘finish.m’ file is and how MATLAB uses it. The source code developed in this tutorial is available at this page.


Your friends may need this knowledge to complete a task. Share this tutorial.