mardi 2 décembre 2014

Custom command to represent $L_1$ metric distance that works both inside and outside math mode


I'm trying to write to define \ds(a,b) so that it results in $||a - b||_1$. This should also work inside a math environment e.g. as part of an inequality statement, but I should be able to use it in the body of the text as \ds(a,b) without enclosing it in $$.


So far, I've managed this, browsing other similar questions in Tex.SE:



\def\ds#1{\innerds(#1)}
\def\innerds(#1,#2) {\ensuremath{||#1 - #2||}\xspace}


This works to a certain extent - I can write \ds(a,b) as part of text, but for some reason, I get the following error when I use it inside math mode:



! Paragraph ended before \innerds was complete.
<to be read again>
\par
l.43

! Missing $ inserted.
<inserted text>
$


MWE (that I've tried) is given below:



\usepackage[fleqn]{amsmath}
\usepackage{amssymb}
\usepackage{xspace}

\def\ds#1{\innerds(#1)}
\def\innerds(#1,#2) {\ensuremath{||#1 - #2||_1}\xspace}

\begin{document}
Outside math mode: \ds(a,b)
Inside math mode: $\ds(a,b)$
Inside displaymath:
\[ \ds(a,b) + \ds(b,c) \geq \ds(a,c) \]
\end{document}




Aucun commentaire:

Enregistrer un commentaire