[Tex/LaTex] Write mathematics in a caption

math-mode

Sometimes I want to write mathematics (like \in – is an element of).
While the element-sign is shown, LaTeX shows errors when compiling saying:

Missing $ inserted.

Extra }, or forgotten $.

Missing } inserted.

When then surrounding any \in with \[ and \] it adds a blank line before and after the line containing \in. I only want to have the simple sign, not the additional space.

This is my code without \[\] around the \in:

\documentclass[11pt, a4paper]{article}
\usepackage[portrait, margin=1in]{geometry}
\usepackage{amsmath}
\usepackage[linesnumbered,ruled]{algorithm2e}

\begin{document}
\begin{algorithm}
    \SetKwInOut{Input}{Input}
    \SetKwInOut{Output}{Output}

    \underline{function myAlgo} $(G)$\;
    \Input{A Graph $G = (V, E)$ with v in V}
    \Output{nothing yet}
    \tcp{does it for ever v in V}
    doSth()\;
    return $G$\;
    \caption{Does sth for every vertex v \in V}
\end{algorithm}
\end{document}

Best Answer

what you probably want is $v \in V$.

the \in must be in math mode (the part inside $...$ as you have already used correctly for $G = (V, E)$). since \in is recognized as math, tex will switch into math mode if it isn't already there, and will therefore report a missing $ when it encounters something that can't be math.

this is an elementary principle of tex, so reading a good introduction would be a good idea. i recommend the books by nicola talbot. some other good advice is given at Why should I buy a TeX/LaTeX guide book?.