19

I want to save everything in the "Command Window" to a file automatically. Is there a way to do it?

gnovice
  • 125,304
  • 15
  • 256
  • 359
Mohammad Moghimi
  • 4,636
  • 14
  • 50
  • 76
  • 1
    By "command window", you mean the textual contents of the window, or the contents of the local workspace? – eykanal Apr 29 '11 at 14:29

1 Answers1

26

You have a few options available for saving content from the Command Window:

  • You can do this using the DIARY command. You could even automate this so that it always records what you do by modifying your startup.m file to turn on text logging:

    diary('myTextLog.txt');  %# Text will be appended if this file already exists
    

    And then modify your finish.m file to turn logging off:

    diary('off');
    

    This will automatically store the entire text content of the Command Window for every MATLAB session, which could grow into a rather large text file.

  • Another option besides using the DIARY command and modifying your startup.m and finish.m files is to start MATLAB using the -logfile option:

    matlab -logfile "myTextLog.txt"
    

    Although I'm not sure if this will overwrite the text file or append to it each time you start MATLAB.

  • If you're just wanting to save the output from evaluating one or more expressions, you can use the EVALC function to evaluate a string containing your expression and capture the output that would normally go to the command window in a character array. You can then print this character array to a file using FPRINTF.

  • Finally, if you're not interested in saving the displayed output from commands you type, but you instead just want to store the commands themselves, then the Command History is what you want. MATLAB automatically stores a history.m file with a maximum size of 200,000 bytes, deleting the oldest entries when newer ones are added.

gnovice
  • 125,304
  • 15
  • 256
  • 359
  • 6
    Note that this needs to be called at the start the session; it will only save all output occurring after the diary command was called. – eykanal Apr 29 '11 at 14:30
  • 1
    Just add diary to startup.m. http://www.mathworks.com/help/techdoc/ref/startup.html Then just generate a new diary file name based off the launch time or something. – Chris Apr 29 '11 at 16:40
  • 1
    In Octave, type `history_file` to see the path where the history is being saved. – Evgeni Sergeev May 19 '13 at 06:15
  • The equivalent of the above for MATLAB is [`prefdir`](http://www.mathworks.com/help/matlab/ref/prefdir.html). – iled Jan 19 '17 at 00:10
  • If you go for the diary solution and you want to name the diary file based on any variable, use `diary(filename)`, e.g. `diary([datestr(now,'yyyymmdd_HHMM'),'.txt])`. Otherwise, `diary filename` will simply take `filename` as name (https://stackoverflow.com/a/22149660). – Rantanplan Mar 24 '22 at 13:24