# Using \newcommand to shortcut math mode $…$ with text spacing issues

(New to LaTeX, so please explain solutions in detail and with examples)

I have many N_{(s)}, N_{(s,a)}, R_{(s)}, R_{(s,a)}, etc in my report.

These are also often integrated with other equations: $Q_{(s)}=\frac{R_{(s)}}{N_{(s)}}=\frac{rewards}{visits}$


For example, using the newcommand and the following in my LaTeX file:

\newcommand{\Ns}{$N_{(s)}$}
........
........
Technology \Ns has given us


gives a PDF result of:

Lastly, how would I integrate \Ns with other equations? I want something like

$\Qs=\frac{\Rs}{\Ns}=\frac{rewards}{visits}$

• Use \ensuremath{...} instead of $...$. For the spacing issue, check xspace, there are also many alternatives to xspace implemented on this site. – Weijun Zhou Apr 26 at 1:17
• The standard approach is to invoke it as \Ns{} with the space following the closing brace. – Steven B. Segletes Apr 26 at 1:34
• Or {\Ns} , depending on your style. Anyway I ended up with xspace. – Weijun Zhou Apr 26 at 1:39

I recommend not putting $...$ inside these macros, both because I think that it is always better to explicitly enter and exit math-mode and because it will break syntax highlighting in your editor. As it pointed out in the comments, if you really want to do this then use \ensuremath.

Depending on how often you use these commands, with the \Rs macros I would use an optional argument:

\newcommand\Rs[1][s]{R_{(#1)}}


Now, $\Rs$ will produce $R_{(s)}$ and $\Rs[s,a]$ will produce $R_{(s,a)}$.


\end{document}
`