How to include MATLAB code in LaTeX documents

Many packages exist that allow you to include source code of different programming languages into LaTeX document. The most popular once are probably listings and fancyvrb. However, due to their aim for being as general as possible, including MATLAB source code with the right color and markup can be tedious task. Fortunately, Florian Knorn over at MATLAB Central developed a simple style file that does this for you: meet mcode.

Set up

Download mcode.sty by clicking this link to the MATLAB Central File Exchange. If that link every breaks down, I’ve uploaded the file to the server as well: here.

Now, put the mcode.sty file in the same folder as the (master) .tex file you’re compiling. Also include the following line of code in your preamble:


Some options could be added between the square brackets:

  • bw: For black and white printing (highlighting will be done based on grayscale)
  • numbered: For numbered lines
  • framed: Puts a frame around each piece of code
  • final: This one is for the case where the draft option is enable in the documentclass. The package will then output no code at all, unless the final option is included.

Note that the mcode package is based on the listings package (it just includes some predefined setup such that the markup and color is according to the MALTAB standard).


Including MATLAB code can be done in two ways. First, just including the code by copy and pasting:

a = 1;    % MATLAB comment
b = 2;
c = a^2 + b^2;

The second option is to include the source code right away from the .m file:


That’s all about the mark up of MATLAB source code in LaTeX documents.


  1. Dick Gilchrist says:

    Thanks for posting this. It works great. I like it when things such as this just work and you don’t have to argue with the computer for hours! :D

  2. Phillipe says:

    I need to include special characters like: ‘é’, ‘ç’, ‘ã’, ‘õ’.

    These characters are being ignored by my compiler.

  3. Chao says:

    Thank you. It is really hepful

  4. YJ says:

    Thank you for this great usepackage.

    But i have a problem with lines over 999 and the frame.

    For example: 1|000

    The line is over the 1. Is there a way to solve this without removing the frame?

  5. Lubomir says:

    Thank you.

  6. Parth Swaroop says:

    Does this work for share latex as well ?

  7. Jo says:

    Thank you so much. This is amazing!

  8. Name (required) says:


    Please add the third way to include MATLAB code inline:

    Chicken chicken \mcode{for k=1:N, disp(k); end} duck duck.

  9. anonymous says:

    Thank you very much. It helped me when I most needed it!

  10. Amin says:

    This works easily and perfectly. I used it with and worked flawless. Thanks

    • Meadhbh says:

      Hi Amin, how do you get it to work on Really stuck, would appreciate any help!

      • Til says:


        i hope it is not to late – it does work in sharelatex. Just download the file under the link “here”, and upload the file mcode.sty in the sharelatex environment just as you would a picture. Then use the packages


        and you are all set!

  11. Zynk says:

    First of all, thank you so much for sharing this, it really came in handy to me and it works perfectly and easily.
    Just a small question, how could I make the Matlab lines indented? I have three code lines between \begin{lstlisting} and \end{lstlisting}, and I would like them to be aligned with the text lines that are indented (so the first line of a normal text paragraph).
    Thank you

  12. We are a bunch of volunteers and starting a new scheme in our community.

    Your web site provided us with valuable info to work on.
    You’ve performed an impressive activity and our whole community will likely be grateful to you.

  13. M says:

    Please cull the spam. It really detracts from your page.

  14. Wow, awesome blog layout! How lonmg have you been blogging for?
    you made blogging look easy. The overll loook of your site is wonderful, let alone the content!

  15. Magnificent goods from you, man. I have understand your stuff previous to and you are just too excellent.
    I actually like what you’ve acquired here, really like what you’re saying and the way
    inn which you say it. You make it enjoyable and you stkll
    take care of to keep it wise. I cant wait to read much more from you.
    This is actually a tremendous web site.

  16. When someone writes an paragraph he/she maintains the plan of a
    user in his/her mind that how a user can undewrstand
    it. So that’s why this paragraph is perfect. Thanks!

  17. drug Rehab says:

    It’s awesome to visit this site and reading the views of all mates concerning this paragraph, while I am also eager of getting know-how.

  18. Miranda says:

    that is so red-hot that even IT has burst into flames.
    Thurston is currently King Roger’s entertainments manager and has
    to travel to Italy (I am doing it again. Batsmen whacking the bowlers,
    bowlers uprooting stumps and what not.

  19. With these types of educational grants, you have the option to pursue your
    dream job and live a better life in the future.
    This is the high time to be self-employed as the entire woorld is going through an economic recession. A short budget matrix should be included in the letter.

  20. I was curious if you ever considered changing the page layout of your site?
    Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with
    it better. Youve got an awful lot of text for only having
    one or 2 pictures. Maybe you could space it out better?

  21. Petra says:

    Ask if there are siode effects from their preferred method of elimination. During the fall months, insects begin looking for warmer
    places to spend the night and where they can spend the winter.
    One thing they all agreed on iis they preferred she come to them,
    not they too her.

  22. I enjoy what you guys tend to be up too. This kind of clever work and exposure!
    Keep up the amazing works guys I’ve incorporated you guys to my personal blogroll.

  23. live scorer says:

    Hi colleagues, its impressive paragraph on the topic of teachingand entirely defined, keep it up all
    the time.

  24. If you don’t have an existing credit card merchant account,
    the app’s owner will help get one through their company. It also
    happens to be the only PA-DDS Certified App in the i
    – Tunes App Store. With all its nifty and useful features, Jot – Not
    deserves to get an award as one of the top business i –
    Phone apps.

  25. google says:

    Extensions can provide both fun and function, but you probably don’t
    need them all. – A Video alert is an email aggregate of the latest videos
    that contain the search terms of your choice and appear in the top ten results of your Google Video search.

    I would not want Sid to pass through the rigours and mistakes that I passed through.

  26. Audun says:

    Is there no way to get the actual line numbers of the code when including a snippet from a larger m-file? All I can make LaTeX do, is extract the correct code, but numbering the lines from 1-, even if the code lines that is extracted actually start at some line 300 something running to line 400 something. That is not really very useful when referring to code within a large file…
    Otherwise a very informative and clearly written post. Thank you! Hoping someone can help me with the last detail :)

    • Audun says:

      Doh, only had to ask to find the answer myself… :)
      \begin{lstlisting}[firstline=348, lastline=353, firstnumber=348]
      Thanks anyway, your post pushed me in the correct direction!

      • Audun says:

        Sorry, that was the wrong code. This is the correct solution:
        \lstinputlisting[language=Matlab, firstline=348, lastline=353, firstnumber=348]{relative/path/to/yourfile.m}

        The firstline/lastline selects the code lines, the firstnumber sets the counter to whatever you set it to… :)

  27. Your method of describing the whole thing in this post is
    genuinely good, every one be able to simply be aware of it, Thanks a

  28. They aren’t cheap however, they must be doing something
    right if they are thus favored. Even though us younger folks lead very busy lives, there are a few simple things we
    can do to restore a sense of value and self-worth to the elderly.
    Rowling states, “They’re very British books, so on a very practical note Harry was going to find biblical quotations on tombstones
    …[but] I think those two particular quotations he finds on the tombstones at Godric’s Hollow, they sum up – they almost epitomise the
    whole series”.

  29. Franklyn says:

    This seems to have issues with the single quote transpose operator. any fix for that ?

  30. Velibor says:

    I followed the “cookbook” step by step but for me it doesn’t work, in the place of the text where the script should be I have blank paper or some dashes… weird. Anyone know whats going on?

  31. If it just contains settings for Matlab, best would be to submit an official patch to the maintainer.

    As far as I can tell the current solution is quite sub-optimal if one has listings from different languages. Besides that it would be a good idea to keep it in one package.

    • Frits says:

      I agree. However, this is a way to go when you just want to display some MATLAB source code in the correct markup without setting up the style yourself. It could be useful for (lab) reports and homework assignments.

  32. Ben Abbott says:

    Will the mcode.sty file be added to CTAN?

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>