You can save the content of the MATLAB Command Window by using the built-in diary
function.
Using the diary
Function
The diary
function allows you to log the interactive session in the Command Window. When logging is on, MATLABĀ® captures entered commands, keyboard input, and text output from the Command Window. This is the primary method for saving your session history and output.
It saves the resulting log to the current folder as a UTF-8 encoded text file named diary
by default.
Starting and Stopping Logging
To begin saving your Command Window session, you simply turn the diary
function on.
- Start logging:
diary on
This command starts logging and saves the output to the default file named
diary
in your current working folder. - Stop logging:
diary off
This command stops the logging session and closes the diary file.
Saving to a Specific File
Instead of using the default filename diary
, you can specify a custom name for your log file.
- Start logging to a specific file:
diary('my_session_log.txt')
This command starts logging and saves the session to a file named
my_session_log.txt
in the current folder. You can include a full path if you want to save it elsewhere. - Append to an existing file:
diary('my_session_log.txt', 'append')
This command starts logging and appends the new session content to the end of
my_session_log.txt
. If the file doesn't exist, it creates it.
Important Tip from Reference
According to the reference, to ensure that all results are properly captured, disable logging before opening or displaying the resulting log. This means you should run diary off
before you open the diary file in a text editor or MATLAB's editor.
Summary of diary
Commands
Here is a quick overview of the most common diary
commands:
Command | Description |
---|---|
diary on |
Starts logging to the default file diary . |
diary off |
Stops logging and closes the diary file. |
diary('filename') |
Starts logging to the specified filename . |
diary('filename', 'append') |
Starts logging and appends to the specified filename . |
diary |
Toggles logging (turns it on if off, and off if on) using the last filename. |
Using diary
is an effective way to keep a record of your MATLAB interactions for debugging, documentation, or sharing. Remember to turn it off when you are done logging.