# Numbering equations in sections and sub-sections

In general, I would like to number equations using the sub-section number, so for example, if I am in sub-section 2.3, then it should number the first equation in this section (2.3.1). To do this, I attempted to simply place \numberwithin{equation}{subsection} in the preamble. The problem' (or rather, un-desirable behavior) with this however, is that, when I am only in a section before having entered a sub-section, it lists the sub-section number as 0, when I would prefer if it simply repressed this.

For example, see the following MWE. The second equation is numbered correctly', whereas I would prefer it if the first equation were numbered simply (1.1).

\documentclass{article}

\usepackage{amsmath}

\numberwithin{equation}{subsection}

\begin{document}

\section{Section}

$$E=mc^2.$$

\subsection{Sub-section}

$$E=\hbar \omega .$$

\end{document}


\let\oldsection\section% Store \section
\renewcommand{\section}{% Update \section
\renewcommand{\theequation}{\thesection.\arabic{equation}}% Update equation number
\oldsection}% Regular \section
\let\oldsubsection\subsection% Store \subsection
\renewcommand{\subsection}{% Update \subsection
\renewcommand{\theequation}{\thesubsection.\arabic{equation}}% Update equation number
\oldsubsection}% Regular \subsection


to your preamble. The above commands update \section and \subsection to adjust \theequation - the equation number printing mechanism - to insert either \thesection or \thesubsection as part of the equation number.

\documentclass{article}

\usepackage{amsmath}

\numberwithin{equation}{subsection}

\let\oldsection\section% Store \section
\renewcommand{\section}{% Update \section
\renewcommand{\theequation}{\thesection.\arabic{equation}}% Update equation number
\oldsection}% Regular \section
\let\oldsubsection\subsection% Store \subsection
\renewcommand{\subsection}{% Update \subsection
\renewcommand{\theequation}{\thesubsection.\arabic{equation}}% Update equation number
\oldsubsection}% Regular \subsection

\begin{document}

\section{Section}

$$E=mc^2.$$

\subsection{Sub-section}

$$E=\hbar \omega .$$

\end{document}


For a more general approach (per-section type equation numbers), you could patch \@startsection directly using etoolbox:

\usepackage{etoolbox}
\makeatletter
\patchcmd{\@startsection}% <cmd>
{\if@noskipsec}% <search>
{\csgdef{theequation}{\csname the#1\endcsname.\arabic{equation}}\if@noskipsec}% <replace>
{}{}% <success><failure>
\makeatother


\@startsection is used by every sectional command (when not using adjustments caused by certain packages) to set the sectional heading. Additionally, the first argument #1 contains the sectional unit name (see Where can I find help files or documentation for commands like \@startsection for LaTeX?).

We patch this macro to use #1 as part of the counter updating, adding the prefix \csname the#1\endcsname. to the equation number.