[Tex/LaTex] MATLAB Command Window Output

MATLAB

I want the Matlab code output to be printed in my LaTeX file.

What is the best and most efficient way to do that? Export results as .txt and then call it in LaTeX or are there other (better) methods to achieve this?

Best Answer

You pretty much have already outlined the work flow. I am assuming you mean the output that appears in the command window.

  1. Get MATLAB to write to a text file, see e.g. this function
  2. Then, include this text file into your document. This could be done by a simple \input command, although, I would recommand treating the MATLAB generated text no different as you would treat source code. There is plenty of choice for including source files into latex, e.g. the listings package.

Here is a minimal example. Place both files in the same directory, run the MATLAB script - works also with octave - and then run latex.

You may notice, that only the output generated between diary on and diary off ends up in the log-file, which is later included into the latex document. This gives you control over what portions of the generated output to put into your document.


Make MATLAB update the latex file:

If you add e.g. system('latexmk --pdf matlabLog') to the end of your MATLAB script, then MATLAB will execute the command specified in the string, which is passed to the system command. In this example I use the latexmk command, can be found here. Alternatively, you could also execute a shell script or any other build magic.


Here is some minimal MATLAB code:

disp("This is a simple test")

% uncomment to erase log
% by default diary appends new data
%delete("matlabDiary.txt")

diary("matlabDiary.txt")
diary on

x = 5;
y = 3;

disp(["x + y = ",num2str(x+y)])

diary off


disp(["x - y = ",num2str(x-y)])

diary on


disp(["x * y = ",num2str(x*y)])

diary off

And some minimal latex code:

\documentclass[11pt,a4paper]{article} 
\usepackage{listings}

\begin{document}
\section{test}

bla bla

\lstinputlisting{matlabDiary.txt}

\end{document}
Related Question