I want to create a newcommand \vecty
to create a vector which will take 3 parameters
like \vecty{1}{2}{3}
and this should display as $\hat{i}+2\hat{j}+3\hat{k}$
and if I give \vecty{0}{3}{-3}
then it should show $3\hat{j}-3\hat{k}
.
I am using LaTeX. I would appreciate any guidance that comes how to get through it.
I did try \ifthenelse
code but it turned to be quite hefty.
You can have a look at the code.
But I know that the code is too bad. Hence wanted to understand if there are other ways to implement it. Kindly help I m a newbie.
Best Answer
Here is one way you can do this:
Notes:
This updated version properly handles integer and decimal coefficients of zero (+0, 0.00) or one with leading
+
signs, spurious spaces, and non-numbers in the input (as per the second section of the table above).newtoggle
from theetoolbox
package was used as I prefer that syntax versus the\newif
syntax. But if you don't want to include an additional package it should be pretty straightforward to adapt this to use\newif
or some other conditional methods. This toggle keeps track if a term has already been printed to ensure that a leading positive term does not have a+
.I used the
xstring
package to determine if the number had a leading minus sign, or was zero, but again, this could easily be adapted to not use that package as well.I would recommend that you use this macro as
$\vecty$
- that is you explicitly enter math mode, as used below. If however, you wish to use it without having to enter math mode as per your original question, you should not surround it with dollar signs, but instead use\ensuremath{\LeadingSign #1 #2}
as then it will be useable inside or outside of math mode. To repeat, I am not recommending this as this is clearly a math mode macro. Please see When not to use \ensuremath for math macro? if you disagree.
Further Enhancements:
\vecty
be required to typeset more than three components, one can easily add additional calls to\Display{}{}
for each of the components -- no other changes should be required. Note that this has not been tested.\vecty{-1x}{+0y}{1z}
.pgf
math to do numerical processing of the input so that basic expressions in the coefficients could be simplified. Thepgf
math functions could also be used to convert-0.5
to-\frac{1}{2}
.Code: