2

(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}$

I want to use newcommands like \newcommand{\Ns}{$N_{(s)}$}, but when I integrated the shortcut \Ns in my code with text surrounding it, there is no space between \Ns and the letters after it.

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:

enter image description here

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

$\Qs=\frac{\Rs}{\Ns}=\frac{rewards}{visits}$
  • 2
    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
  • 1
    Or {\Ns} , depending on your style. Anyway I ended up with xspace. – Weijun Zhou Apr 26 at 1:39
2

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)}$.

Finally, you don't want to write \frac{rewards}{visits} as the letters in rewards and visits will look like variables multiplied together. Instead, you should use \frac{\text{rewards}}{\text{visits}}$. The\text` command comes from the amsmath package.

For completeness, here is a MWE:

\documentclass{article}
\usepackage{amsmath}

\newcommand\Ns[1][s]{N_{(#1)}}
\newcommand\Rs[1][s]{R_{(#1)}}
\newcommand\Qs[1][s]{Q_{(#1)}}

\begin{document}

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

\end{document}

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.