i am new in all this Latex stuff, but i am trying to learn. Currently i am stuck in a problem: display a Matlab code.

This is my code in TexStudio:

\usepackage[margin = 2cm]{geometry}

x = 0:0.01:1e2;  %Test Test Test Test Test %Test Test Test Test Test %Test Test Test Test Test %Test Test Test Test Test

y = sin(x);

for i = 1:1:100
    fprintf('Hello World \n')

title('Sin of x')

grid on


In first, i would like to copy the script from Matlab to Latex's environment and then get the code indented in pdf. Currently i am getting it all in the same line.

I also would like to copy the code from the generated pdf back to matlab and be able to run the code, but it just appear messed up, with all the spacements out of place.

Does anyone know how can i do it ?

  • 1
    Welcome to TeX.SE.
    – Mico
    May 3, 2020 at 4:39
  • 1
    Please clarify what you mean by "Currently i am getting it all in the same line". (For what it's worth, when I run your code on a MacBook Air under MacOS 10.15.4 "Catalina" and MacTeX2020, the pdf output occupies about a dozen lines.) On your second question: The answer depends importantly on the pdf browswer you employ. Under Acrobat Reader, I can copy material from the formatted output back into a text editor; the only issues is that all-blank lines are ignored.
    – Mico
    May 3, 2020 at 4:49
  • Try doing a Ctrl+I smart indenting in Matlab before copying your code into the lstlisting environment. Maybe that helps your cause. May 3, 2020 at 8:31


You must log in to answer this question.

Browse other questions tagged .