3

I am trying to put my code into a Latex document using matlab-prettifier. I am doing this by using \lstinputlisting[style=Matlab-editor]{Trap.m}.

An example of Trap.m (a MATLAB file) is as follows

step size = 5
sub_int=100
fprintf("To get an estimation to two decimal places we needed a step size of %f which is %.0f intervals. \n",  step_size, sub_int)

When I run matlab-prettifier it assumes that after '%' the string is actually a comment and not a statement. As it is meant to be inputting a float into a string then the colour should be black. I am unsure how to correct this.

I have included a MWE below for Latex.

\documentclass{article}
\usepackage{matlab-prettifier}
Text...
\lstinputlisting[style=Matlab-editor]{Trap.m}

Output

  • 1
    Instead of a screenshot, could you please post a compilable minimal working example (MWE) that we can work on? – Phelype Oleinik Sep 25 '18 at 15:21
  • I have uploaded a MWE. – KieranSQ Sep 25 '18 at 16:48
  • MATLAB strings (and the first parameter of fprint is one) are delimited by single quotes, not by double quotes. – jub0bs Dec 14 '18 at 15:32
4

You can use single quotes instead of double quotes to wrap the string

Or else you can define some escape character and put '%' inside the escape characters. Here is a MWE.

\documentclass{article}
\usepackage{matlab-prettifier}
\lstset{
escapechar         = `,
    }
\begin{document}
Text...
\lstinputlisting[style=Matlab-editor]{Trap.m}
\end{document}

Trap.m

step size = 5
sub_int=100
fprintf('To get an estimation to two decimal places we needed a step size of %f which is %.0f intervals. \n',  step_size, sub_int)
fprintf("To get an estimation to two decimal places we needed a step size of `\%`f which is `\%`.0f intervals. \n",  step_size, sub_int)

Output: enter image description here

1

Add morestring=[m]" to the lstoptions, using package options (after the language), \lstset, or the optional argument to the listing.

It really ought to be added to the style file, perhaps with a version option so that buggy pre-2017 code is still highlighted "correctly", but CTAN doesn't list a repository so I can't just send a pull request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.