I'm currently using the algorithm
package for typesetting Matlab source code in my document. However, the way keywords are typeset doesn't match the Matlab syntax. For instance, \EndFor
is typeset as "end for" instead of "end", which is the terminating keyword of a for loop in Matlab. How can I fix this?
I have the following code:
\usepackage{algorithm}
\usepackage{algpseudocode}
\floatname{algorithm}
\begin{algorithm}[H]
\begin{algorithmic}\State
alpha=0; rho=0;\State
\For {$r=1:p$}\State
rho=rho+1/(r\^{}2);\State
alpha=alpha+1/(r\^{}4);
\EndFor \State
\end{algorithmic}
\end{algorithm}
Best Answer
Short answer: don't use
algorithm
for typesetting source code. Use either thelistings
orminted
package instead, or (edit) thematlab-prettifier
package; see below.Detailed answer:
You can change the way
algpseudocode
's keywords (such as for, while, etc.) are typeset by redefining them usingalgorithm
's\algdef
command. The following modification answers your specific question about for and end for.However, while reconfiguring
algorithm
& friends to comply with some language's syntax may be possible to an extent (and at the cost of great effort and tedium), those packages are really not intended for anything other than pseudocode (i.e. "algorithms explained in plain English").Other packages such as
listings
orminted
are better suited for typesetting source code (i.e., in your case, the contents of an m-file). Those packages come with predefined settings for numerous programming languages (C, Python, Matlab, etc.), settings which can be customised. Additionally, both of those packages allow for line numbering and syntax highlighting.Edit: I've recently written a package called
matlab-prettifier
for typesetting Matlab code nicely. It's built on top of thelistings
package, but I've defined a style that mimicksminted
output, with overall better syntax-highlighting capabilities; note, in particular, that, in my example, theend
keyword is highlighted differently, depending on the context in which it is used.I've generated the
m
-file fromn within mytex
file, just for completeness of my example. In practice, you would have yourm
-files sitting somewhere on your machine and you would just link to them inside your input file.Finallly, a comment that is only peripheral to the main topic here (TeX): Matlab loops are slow! For improved performance, you should, whenever possible, avoid using Matlab (
for
orwhile
) loops and use, instead, a combination of the colon operator and vectorised commands (such assum
). Here is the alternative I would recommend:The reduction in computation time of my version over yours becomes significant as
p
increases.