4

I'm looking for the way to create new command

\newcommand{\transpose}[1]{#1^T}.

But what is important here I want the command to check if the argument has super- or subscript and add parentheses if necessary. So it should do

#1 == D => \newcommand{\transpose}[1]{#1^T}
#1 == D_1 => \newcommand{\transpose}[1]{\left(#1\right)^T}

I hope it's clear. Do you have some ideas?

1 Answers1

6

This reads the argument as a list of items, with ^ and _ as item delimiters (parsing separators). If either/both are present, the list length will exceed one. I then use the list length to decide whether or not to add parens.

\documentclass{article}  
\usepackage{listofitems}
\newcommand\transpose[1]{%
  \setsepchar{_||^}%
  \readlist\mymat{#1}%
  \ifnum\mymatlen>1\left(#1\right)^T\else#1^T\fi%
}
\begin{document}  
\[
\transpose{D}
\]
\[
\transpose{D_1}
\]
\[
\transpose{D^x}
\]
\end{document}

enter image description here

A single expansion upon the argument, in the form of

\newcommand\transpose[1]{%
  \setsepchar{_||^}%
  \expandafter\readlist\expandafter\mymat\expandafter{#1}%
  \ifnum\mymatlen>1\left(#1\right)^T\else#1^T\fi%
}

would allow some embedded cases to be properly digested, for example,

\def\myvar{A_x}
\[
\transpose{\myvar}
\]

enter image description here