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?

  • Welcome to TeX.SX! Is it for a one-shot input, or should your .tex document be updated when you change your MatLab source code? – ebosi Dec 1 '16 at 12:35
  • Yes my .tex document should be updated. Anything to take care of? – MatlabNewb Dec 1 '16 at 12:56

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

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:



bla bla


  • Thanks mate. I will try that. Thought there is a better and more efficient option to achieve that but I guess I'll stick to this method then :) – MatlabNewb Dec 1 '16 at 12:57
  • Hi, I don't see much inefficiency. On both the MATLAB and the latex side of things, it is some lines of code. Using the listings package allows you to visually and logically set the MATLAB log apart from other text within the document. Once set up, no more manual intervention required. – Dohn Joe Dec 1 '16 at 16:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.