# Define starting line number when using mcode.sty to display Matlab code and referring to the code

I want to include parts of my Matlab code in my LaTeX document using mcode.sty. Here's a MWE:

\documentclass[b5paper, 10pt, twoside, openright, dvipsnames,cmyk]{report}
\usepackage{listings}   % Is this package necessary?
\usepackage[framed,numbered,autolinebreaks]{mcode}
\begin{document}
Figure~\ref{fig:binarysearch} doesnt work!
\begin{figure}
\label{fig:binarysearch}
\lstinputlisting{pics/met/binarysearch.m}
\caption[Matlab code for the half-interval search method]
{Matlab code for the half-interval search method}
\end{figure}
\end{document}


Is there a way to define which line number I want to start on for each included code section? Let's say I want to start on line 6. How is this accomplished? The default is (naturally) 1.

I've placed the code in a figure environment, and I want to refer to it as a figure. However, referring in the text to the figure doesn't work. The compiled file writes ?? instead of the figure reference.

• You should have a look at the matlab-prettifier package; it improves upon mcode in many ways. See this answer, for instance. – jub0bs May 12 '15 at 12:29
• I read your answer, @Jubobs, but I didn't really get the hang of it. What specifically is the difference between mcode and your package? Is it possible to explain it with a few sentences? – ROLF May 12 '15 at 14:34
• There wouldn't be enough space in a Stack-Overflow comment :p I refer you to section 2 of the matlab-prettifier doc, in which you will find a point-by-point comparison of the alternatives (mcode, minted, etc.). Basically, matlab-prettifier aims to be easier to use and more consistent than mcode. – jub0bs May 12 '15 at 16:07
• @Jubobs: When using mcode, there seems to be less space per line in LaTeX compared to Matlab. I've fittet my code into one line in Matlab, but the text must be on two lines in my document. Is this the case for matlab-prettifier too? – ROLF Jun 7 '15 at 19:07
• That has little to do with mcode or matlab-prettifier; rather, it depends on the font (family, size, etc.) and the text width you use; you can use the listings' option called linewidth to tweak the latter to your liking. – jub0bs Jun 7 '15 at 21:04

The following code solves the first question:

\lstinputlisting[firstnumber=6]{{pics/met/binarysearch.m}}


firstnumber defines the starting line number.

The second question: Wrong order of the code. The following code is correct:

\begin{figure}[htb]
\centering
\lstinputlisting[firstnumber=6]{pics/met/binarysearch.m}
\caption[Matlab code for the half-interval search method]
{Matlab code for the half-interval search method}
\label{fig:binarysearch}
\end{figure}