Monday, February 3, 2014

How to insert MATLAB codes into a LATEX document

LATEX can be messy if you don't know what you're doing. Sometimes it's not easy to get used to if you're coming from a Microsoft Office background. It took me a while to figure out how to do different things like creating a table, adding multiple columns, drawing a square around an answer, etc. But once you figure it out, latex gives you remarkable results. Some of the things are not straightforward like in MS Word, but sometimes it's worth taking time to learn how to do things. There are so many resources out there on the internet. Which brings me to this post. I like to use LATEX to do my homework. Sometimes I have to use MATLAB to solve some numerical problems, or to graph something, etc. The professor expect me to submit the MATLAB code with the homework. I can just copy and paste the code from an M-file to the latex document. But it doesn't keep the formatting of the M-File.

To Solve this problem a guy named Florian Knorn at the MATLAB central created a style file which lets you do this very task. He calls it the MCODE. You can download the mcode by clicking this link which will direct you to MATLAB Central.

How to use MCODE:

  • To use mcode, first you have to download it and put it in the same directory as your .tex file which you're trying to compile. 
  • Then, include mcode as a package in your .tex file:
  • \usepackage[]{mcode}
    
  • Some options can be added between the square brackets:
    • bw : Black and White
    • numbered : Number the lines of your code
    • framed : Draw a frame around your code
  • Now to include MATLAB code one of two ways can be used.
  1. Copying and Pasting the MATLAB code:
  2. \begin{lstlisting}
    clear;
    clc;
    len=1000;
    L2=zeros(1,len);
    index=1;
    \end{lstlisting}
    
  3. Using the Path of the M-File:
  4. \lstinputlisting{/path/mfile_name.m}
    

Complete Example:


\documentclass[12pt]{article}
 
\usepackage[numbered, framed]{mcode}
 
\begin{document}

\title{MATLAB Code in LATEX}
\author{Saliya}
\date{} 
\maketitle

Copy and Paste Method:
\begin{lstlisting} 
clear;
clc;
len=1000;
L2=zeros(1,len);
index=1;
\end{lstlisting} 

Using the path of the M-File:
\lstinputlisting{mfile.m}

\end{document}

Result:


No comments:

Post a Comment