Here is the template I use for matlab code:
\documentclass{article}
\usepackage{listings}
\usepackage{color} %red, green, blue, yellow, cyan, magenta, black, white
\definecolor{mygreen}{RGB}{28,172,0} % color values Red, Green, Blue
\definecolor{mylilas}{RGB}{170,55,241}
\begin{document}
\lstset{language=Matlab,%
%basicstyle=\color{red},
breaklines=true,%
morekeywords={matlab2tikz},
keywordstyle=\color{blue},%
morekeywords=[2]{1}, keywordstyle=[2]{\color{black}},
identifierstyle=\color{black},%
stringstyle=\color{mylilas},
commentstyle=\color{mygreen},%
showstringspaces=false,%without this there will be a symbol in the places where there is a space
numbers=left,%
numberstyle={\tiny \color{black}},% size of the numbers
numbersep=9pt, % this defines how far the numbers are from the text
emph=[1]{for,end,break},emphstyle=[1]\color{red}, %some words to emphasise
%emph=[2]{word1,word2}, emphstyle=[2]{style},
}
\section*{Matlab Code}
\lstinputlisting{myfun.m}
\end{document}
This produced the following output (I didn't put my matlab file here but it should be clear from the output):
Do you know tcolorbox
? It was developed to help formating LaTeX tutorials.
Next code uses default settings, from there you can customize almost everything.
\documentclass[11pt,a4paper]{article}
\usepackage[most]{tcolorbox}
\usepackage{lipsum}
\begin{document}
\lipsum[4]
\begin{tcblisting}{listing only}
\begin{equation}
\frac{3}{2}=\frac{a}{b}
\end{equation}
\end{tcblisting}
\lipsum[4]
\begin{tcblisting}{listing side text}
\begin{equation}
\frac{3}{2}=\frac{a}{b}
\end{equation}
\end{tcblisting}
\lipsum[4]
\end{document}
Best Answer
I recommend using
minted
and notlstlisting
as the code is easier to copy from the PDF and run. Copying code fromlstlisting
produces many errors that must be fixed before the code can run. Minted has several styles, so you can chose the one you like the most for highlighting. Overleaf has a Reference guide of all the minted styles. Also, minted supports theoctave
language.Here the code:
Here is the code copied from the
lstlisting
environment:Here is the code copied from
minted
environment:There are also other problems with
lstlisting
that does not show in this example:I once had to copy and run code from the
lstlisting
environment (I only had a PDF) and had fix over 100 mistakes before I could run the code. Almost all of these mistakes could have been avoided usingminted
instead oflstlisting
.