Breaking lines in codes with mcode package
Use \usepackage[autolinebreaks]{mcode}
. Other possible options which may be of interest to you are [framed,numbered,autolinebreaks,useliterate.....]
. For more details, look into the source code of mcode
.
Edit for the revised question.
If autolinbreaks
option is given, mcode.sty
defines lstset
as (line no 231 in mcode.sty of version 2.7.0.0)
\lstset{breaklines=true,breakatwhitespace=true,prebreak=\usebox{\lbreakdots}}
The culprit here is breakatwhitespace=true
. Your formula has no white spaces and hence it will never break at the end of line.
Solution
Add
breakatwhitespace=false
after loading mcode
.
MWE will be
\documentclass{book}
\usepackage{graphicx}
\usepackage{amsmath,amssymb}
\usepackage{caption}
% \usepackage{color,xcolor}
\usepackage[framed,numbered,autolinebreaks,useliterate]{mcode}
\lstset{breakatwhitespace=false} %%<---this line added
\begin{document}
\begin{figure}
\caption{My program for plotting the above formula in 2 different conditions}
\lstinputlisting{technique.m}
\end{figure}
\lstinputlisting[caption={My program for plotting the above formula in 2 different
conditions}]{technique.m}
\end{document}
Note: Instead of putting your code inside figure
environment, you can use the second instance as I showed in the code. The differences are clear, I hope.
Another alternative is the package Listings
(Documentation here). It's very customizable, but for example, this would suffice I think:
\usepackage{listings}
\lstset{
language=Matlab,
breaklines=true
}
You can then embed files using \lstinputlisting{test.m}
. With additional styling parameters, one can produce something like this (these are the contents of test.m
compiled into .pdf):