Math & ScienceRequest for example of an equation macro

Information and discussion about LaTeX's math and science related features (e.g. formulas, graphs).
Post Reply
Singularity
Posts: 156
Joined: Sat Jan 22, 2011 9:55 pm

Request for example of an equation macro

Post by Singularity »

I have several equations (here's one)

Code: Select all

\begin{equation}
  T = \frac{1}{2} \sum_{n=1}^N \dot{u}_n^2
\label{eq:Kinetic}
.\end{equation}
which will be repeated several times in my document. They are likely to change during the writing process. My adviser says I can make a macro so each one exists in only one place. This post is a request for an example of how to make an equation macro (I wasn't sure what to search for online and could not find anything helpful).

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

cgnieder
Site Moderator
Posts: 2000
Joined: Sat Apr 16, 2011 7:27 pm

Request for example of an equation macro

Post by cgnieder »

I once suggested to save equations in a separate file -- let's call it equations.tex -- with a macro \saveequation{<ID>}{<equation code>} and use those equations in the main file via \useequation{<ID>}.

Here is an example:

Code: Select all

\documentclass{article}

% this is the separate file for the sake of this example
% created with {filecontents}:
\usepackage{filecontents}
\begin{filecontents}{equations.tex}
\makeatletter
% \saveequation{<ID>}{<equation>}
\newcommand\saveequation[2]{%
  \@namedef{equation@#1}{#2}%
}

% \useequation{<ID>}
\newcommand\useequation[1]{%
  \@nameuse{equation@#1}%
}
\makeatother
\RequirePackage{amsmath,bm}
\saveequation{massenergy}{E = mc^{2}}
\saveequation{curlE}{\nabla \times \bm{E} = 0}
\end{filecontents}

% input the file:    
\input{equations}

\begin{document}
% usage:
This is Einstein's relation: $\useequation{massenergy}$.
This is the curl of electric field:
\begin{equation}
 \useequation{curlE}\label{eq:curlE}
\end{equation}
and without number:
\[
 \useequation{curlE}
\]

\end{document}
The link above suggests other solutions as well.

Regards
site moderator & package author
Singularity
Posts: 156
Joined: Sat Jan 22, 2011 9:55 pm

Request for example of an equation macro

Post by Singularity »

Thanks. Your info about putting all the equations in another file is good, but made the example more difficult for a LaTeX newbie to understand. But I figured it out and can use it (and using separate files). Here's a pared down example for other newbies.

Code: Select all

\makeatletter
\newcommand\saveequation[2]{\@namedef{equation@#1}{#2}}
\newcommand\useequation[1]{\@nameuse{equation@#1}}
\makeatother
\saveequation{SavedEnergyCalc}{\frac{A^2}{2} \left(N +1 \right) \left( 1 - \cos \frac{\pi}{N+1} \right)}
...
\begin{align}
  H(A,N) &= \useequation{SavedEnergyCalc} \label{eq:EnergyCalc}
.\end{align}
Also, note that saveequation can be used inside the document body.
Post Reply