I am familiar with the \foreach loop in the TikZ pakage. Is there an analogous loop I can use in my preamble? I like to use \M, \A, \I, and other commands as shorthand for matrices. So instead of writing

\renewcommand\S{\mathbf S}    
\newcommand\V{\mathcal V}
\newcommand\E{\mathcal E}
\newcommand\M{\mathbf M}
\newcommand\A{\mathbf A}
\newcommand\z{\mathbf z}
\newcommand\x{\mathbf x}
\newcommand\B{\mathbf B}
\newcommand\I{\mathbf I}
\newcommand\J{\mathbf J}
\newcommand\X{\mathbf X}
\newcommand\Q{\mathbf Q}

Can I do something to the effect of

\foreach \x in {S, V, E, M, A, z, x, B, I, J, X, Q}{
    \newcommand \\x {\mathbf \x}

I'm asking just to make my preamble look a bit cleaner. I'm open to other suggestions too.

3 Answers 3


The following is a way to use a for loop in LaTeX which doesn't require any packages:


  \expandafter\newcommand\csname my\cs\endcsname{}% check whether the command is already defined
  \expandafter\edef\csname my\cs\endcsname{\noexpand\mathbf{\cs}}% define it expanding \cs

  • How would one go about creating a similar loop to define multiple \newtheorem envirnoments? Commented Dec 5, 2017 at 20:14
  • I'd probably go a similar way to daleif's. Create a command which takes the theorem-name as an argument and defines it. Then call that command in a \@for-loop with \expandafter\MyNewTheorem\expandafter{\cs}.
    – Skillmon
    Commented Dec 5, 2017 at 20:27
  • @LukeCollins You could as well use your \@for-loop with \@for\cs:={{name1}{description1},{name2}{description2}}\do{\expandafter\newtheorem\cs}. But for that, I think this is obfuscating and \newtheorem{name1}{description1}\newtheorem{name2}{description2} is better.
    – Skillmon
    Commented Dec 5, 2017 at 20:34

Similar to Skillmon, but using etoolbox for simpler code. I also recommend prefixing the macros to avoid unintentionally overwriting build in macros.

This can easily be adapted to also make others.

    \typeout{Cannot make \string\bf#1, already exists, ignoring}




If you want clean syntax, expl3 is for you.


\ExplSyntaxOn % access the programmer's level

 { S, V, E, M, A, z, x, B, I, J, X, Q }
  \cs_new_protected:cpn {b#1} { \mathbf{#1} }


This will define \bS, \bV and so on. Avoid redefining commands such as \S. If you want to be on the risky side, use \cs_set_protected:cpn instead of \cs_new_protected:cpn, but then blame yourself if something goes wrong.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .