Skip to main content

LaTeX Guide

Introduction to LaTeX

LaTeX is a professional typesetting system based on the TeX engine, developed by Leslie Lamport. It uses plain text to compose documents and compiles them into PDF, allowing authors to focus on content rather than layout details. It excels at mathematical formulas and bibliography handling, and is the mainstream typesetting tool for scientific and technical papers in STEM fields.

Packages: LaTeX's extension library, loaded in the preamble with \usepackage{package-name}, used to add functionality not available natively, such as Chinese rendering, formulas, and graphics.

Features of LaTeX

  • High-quality typesetting: LaTeX is renowned for its professional typesetting quality, especially for complex mathematical formulas and bibliographies. It automatically adjusts document formatting to produce publication-standard output.
  • Markup-based: LaTeX uses a plain-text markup language. Users define document structure and formatting with specific commands and tags. For example, use \section{} for sections and \textbf{} for bold text.
  • Cross-platform support: LaTeX is cross-platform, supporting Windows, macOS, and Linux. Generated documents are usually PDF and display consistently across platforms.
  • Suitable for academic writing: LaTeX is ideal for writing academic papers, books, technical documents, and reports, especially those with many mathematical formulas, references, and complex layout requirements. It offers excellent support for bibliography management, formula input, and typesetting effects.
  • Automated document management: LaTeX provides powerful automation for long documents, books, and papers, such as automatic numbering, table of contents generation, cross-references, and formula typesetting. It can automatically handle citations and reference lists, making it ideal for documents requiring precise formatting.

LaTeX vs. Word

FeatureLaTeXMicrosoft Word
Typesetting qualityProfessional-grade, especially for complex formulas and long documents.Suitable for simple documents; complex layouts require manual adjustment.
Learning curveRequires learning basic syntax; steeper at first.WYSIWYG, easy to get started.
AutomationAutomatic numbering, cross-references, table of contents, etc.Manual numbering and formatting required.
Math formula supportPowerful formula typesetting, supporting complex symbols and structures.Limited formula editor; complex formulas are difficult.
Cross-platform supportFully cross-platform, consistent document rendering across systems.Good cross-platform support, but formatting may vary by version.
Document structureContent and formatting separated, easier maintenance and collaboration.Content and formatting mixed, harder to maintain long documents.
ExtensibilityExtend functionality via packages, support custom commands and environments.Feature extensions rely on plugins, less flexible.

LaTeX Workflow

  1. Write LaTeX source code: Use a plain text editor to write .tex files containing document structure, text, and commands.
  2. Compile LaTeX source code: Use a LaTeX compiler (such as pdflatex, xelatex, lualatex, etc.) to compile the source code into a PDF file.
  3. Preview the PDF file: Use a PDF reader to preview the compiled PDF file; the content is automatically typeset according to the source code.
  4. Modify the source code: Modify the LaTeX source code as needed, and repeat the compile and preview steps until satisfied.

Basic Syntax

Basic Structure of a LaTeX Document

A complete LaTeX document is divided into three parts: document class declaration, preamble, and body.

  • Document class: defines the overall document type (article, report, book)
  • Preamble: before \begin{document}, where packages are loaded and global settings are configured
  • Body: between \begin{document} and \end{document}, containing all main content
  • % is the comment symbol; the rest of the line will not be compiled
\documentclass{article}
% Preamble: load packages
\usepackage{ctex} % Chinese support package
\usepackage{amsmath} % Math formula package

\begin{document}

Hello, LaTeX!

This is a minimal example document.

\end{document}

Hello, LaTeX!

This is a minimal example document.

Common document classes:

  1. article: short articles, conference papers
  2. report: course reports, theses, supports chapters
  3. book: book typesetting

Document Structure and Layout

Document structure and layout address the "skeleton" of a document: how the title is set, how sections are divided, how the table of contents is generated, and how page layout and headers/footers are configured. These settings only need to be configured once and take effect throughout the document—this is the core advantage of LaTeX for long documents.

Title, Author, and Date

Three steps: declare the information in the preamble, then call \maketitle in the body to render it.

\documentclass{ctexart}

\title{Paper Title} % Title (required; must be defined to render the title area)
\author{Zhang San \and Li Si} % Authors; \and separates multiple authors
\date{\today} % Date: \today for today; {} empty argument hides the date

\begin{document}

\maketitle % Render the title area here (centered title, author, date)

\end{document}

CommandPurposeCommon Usage
\title{...}Declare titleManual line breaks with \\ allowed in title
\author{...}Declare authorZhang San \and Li Si; \thanks can add affiliation footnotes
\date{...}Declare date\today for today; fixed date handwritten; {} to hide
\maketitleRender title areaPlace at the beginning of the body

Section Commands and Automatic Numbering

Sections are the basic units of structured documents. LaTeX uses a set of commands to express hierarchy, and numbering is fully automatic.

CommandLevelApplicable Document Classes
\part{...}Part (level 0, independent numbering)article / report / book
\chapter{...}Chapter (level 1, starts on a new page)report / book only
\section{...}Section (level 1 in article)all
\subsection{...}Subsection (level 2)all
\subsubsection{...}Subsubsection (level 3)all
\paragraph{...}Titled paragraph (unnumbered)all

Two things best demonstrate the value of "automatic": first, inserting a new section in the middle automatically renumbers subsequent sections; second, adding a star (e.g., \section*{...}) means unnumbered and not included in the table of contents.

Example: Sections and footnotes

\documentclass{ctexart}
\begin{document}

\section{Introduction} This is the introduction content. All section numbers are generated automatically by LaTeX.

\subsection{Research Background} Research background is introduced here\footnote{This is a footnote; numbering and layout are automatic.}.
\subsection{Research Significance} Research significance is explained here.

\section{Method}
\subsection{Data Collection}
\subsubsection{Sample Selection} Hierarchy reaches the subsubsection level.
\subsection{Model Design}

\section{Conclusion}

\end{document}

\footnote{footnote content} places a marker at the current position and moves the content to the bottom of the page; numbering is continuous throughout the document, so footnotes cannot be nested inside other footnotes.

Generating a Table of Contents

A table of contents requires only one command: \tableofcontents. It scans all section commands in the document and automatically generates a page-numbered table of contents.

Example: Generating a table of contents

\documentclass{ctexart}
\renewcommand{\contentsname}{Contents}

\begin{document}

\tableofcontents
% Table of contents on its own page; body starts on the next page
\newpage

\section{Introduction}
Introduction content.

\subsection{Research Background}
Research background is introduced here.

\section{Method}
Method content.

\section{Conclusion}
Conclusion content.

\end{document}

Table of contents page numbers rely on the .aux file for propagation, so after adding new sections the table of contents may not be immediately correct; just compile again.

To control the depth of the table of contents, set in the preamble: \setcounter{tocdepth}{2} means only subsections are included; with \setcounter{secnumdepth}{2} you can simultaneously control numbering depth in the body.

Page Layout: The geometry Package

Page margins, paper size, and other page parameters are managed uniformly by the geometry package.

Example: Common page settings

% Option 1: options directly in the square brackets before the package name (most common when there are few options)
\usepackage[a4paper, margin=2.5cm]{geometry}

% Option 2: load first, then set centrally with \geometry (clearer when there are many options)
\usepackage{geometry}
\geometry{
a4paper, % Paper: A4
margin=2.5cm, % Uniform 2.5 cm margins on all sides
includefoot % Include footer in the type area to avoid footer "hanging" outside the margins
}

A4 page with 2.5 cm margins on all sides.

The type area (controlled by the geometry package; see the compiled PDF for the actual effect).

The two writing styles produce exactly the same result; choose either. Note that package options always go in square brackets []—writing options in curly braces {} is a common beginner mistake.

OptionMeaningExample
marginUniform margin on all sidesmargin=2.5cm
top / bottom / left / rightControl one side individuallyleft=3cm,right=3cm
a4paper / a5paper / letterpaperPaper sizea4paper
landscapeLandscape pageFor wide slides or wide tables
textwidth / textheightDirectly specify type area width/heighttextwidth=15cm

For domestic theses, the "symmetric odd-even binding" is common: add bindingoffset=1cm to leave an extra 1 cm on the binding edge.

Headers and Footers: The fancyhdr Package

fancyhdr divides headers and footers into left, center, and right slots; you can fill them with whatever you want.

CommandControlled Slot
\fancyhead[L]{...}Header left
\fancyhead[C]{...}Header center
\fancyhead[R]{...}Header right
\fancyfoot[L]{...}Footer left
\fancyfoot[C]{...}Footer center
\fancyfoot[R]{...}Footer right

Example: Classic academic header and footer

\documentclass{ctexart}
\usepackage[a4paper, margin=2.5cm]{geometry}
\usepackage{fancyhdr}

\pagestyle{fancy} % Enable fancyhdr page style
\fancyhf{} % Clear all slots first to avoid residual default page numbers
\fancyhead[L]{\nouppercase\leftmark} % Header left: current top-level section name
\fancyhead[R]{Page \thepage} % Header right: page number
\fancyfoot[C]{ LaTeX Guide} % Footer center: custom text
\renewcommand{\headrulewidth}{0.4pt} % Thickness of the line below the header

\begin{document}

\section{Page Layout}
The distance between text and page is controlled by the geometry package, including margins, paper size, and header/footer areas.
Reasonable page margins make documents more readable; academic documents usually require about 2.5 cm top/bottom and 2.5 cm left/right.
Once page layout parameters are set in the preamble, they take effect automatically throughout the document; no per-page adjustment is needed.

\section{Headers and Footers}
fancyhdr divides the header and footer into left, center, and right slots, allowing free combinations.
Headers often hold section names and page numbers, while footers often hold page numbers or document names; academic journal templates have strict rules.
Page numbers increase automatically with each page; page numbers in cross-references are also provided by it.

\end{document}

\markright and \leftmark are two "dynamic bookmarks"; when typesetting each page, LaTeX automatically records the current section and writes it into the corresponding bookmark; page numbers are updated accordingly.

CommandPurposeUsage Suggestion
\newpageEnd current page, continue from new pageRecommended for daily use
\clearpageNew page and first output all pending floatsSafer at end of chapters or document
\linebreakForce line break here with justified alignmentUse sparingly; let LaTeX break lines automatically
\pagebreakSuggest a page break here (contrast with \nopagebreak)Use sparingly

Do not frequently use \newpage to "align" pages—let LaTeX paginate automatically so the document does not become misaligned when edited. Manual page breaks are only for structural breakpoints, such as after the table of contents or between chapters.

Summary

FunctionCommand / PackageLocation
Title area\title / \author / \maketitleDeclared in preamble, rendered in body
Sections\section / \subsection / \subsubsectionBody
Footnotes\footnote{...}Body (usually right after text)
Table of contents\tableofcontentsAfter preamble, before body
Page marginsgeometry packagePreamble
Headers/footersfancyhdr packagePreamble

Text Formatting and Lists

Text formatting and lists handle the "flesh and blood" of the body: how to switch font styles, adjust font sizes, use the three list environments, and control alignment. The principle remains the same: these are semantic commands. You tell LaTeX "this is emphasis," and the document class decides exactly how it looks.

Font Styles

There are five commonly used styles, all in the form of "command + braces," acting on the text inside the braces.

EffectCommandDescription
Bold\textbf{...}bold face
Italic\textit{...}Chinese is automatically mapped to Kai typeface
Underline\underline{...}Use with caution in formal typesetting; Western convention prefers italics
Monospace\texttt{...}typewriter, for code, commands, and file names
Emphasis\emph{...}Smart emphasis: italic in normal text, upright in italic text

Example: Font styles

\documentclass{ctexart}
\begin{document}
\textbf{Bold text}、\textit{Italic text}、\underline{Underlined text}、\texttt{Monospace text}.

Chinese emphasis uses \emph{key point}, English emphasis uses \emph{emphasis}.

Combined use: \textbf{bold and \textit{italic}}, \texttt{code can also be \textbf{bold}}.
\end{document}

Note a detail in the output: Chinese "italics" actually display as Kai typeface—Chinese characters have no italic tradition, so ctex automatically uses Kai to take on the emphasis role. This is the correct localized handling. The difference between \emph and \textit lies in "intelligence": inside text that is already italic, \emph automatically switches back to upright to create contrast. Prefer \emph when writing papers.

Do not use underlines for emphasis—that is a relic of the typewriter era. In academic typesetting, italics or bold are sufficient.

Font Size Adjustment

Western font sizes are a set of "declarative" commands, ten levels from \tiny to \Huge, scaled proportionally from \normalsize.

From small to largeCommand
1–5 (small)\tiny, \scriptsize, \footnotesize, \small, \normalsize
6–10 (large)\large, \Large, \LARGE, \huge, \Huge

Example: Font sizes and Chinese font sizes

\documentclass{ctexart}
\begin{document}
{\tiny tiny footnote-level}、{\scriptsize scriptsize}、{\footnotesize footnotesize}、{\small small}、body default \normalsize.

{\large large}、{\Large Large}、{\LARGE LARGE}、{\huge huge}、{\Huge Huge}.

% Chinese theses more commonly use "hao" numbers directly: \zihao{number}
Chinese font sizes: {\zihao{5} size 5 (commonly used for body)}、{\zihao{-4} small 4 (thesis body)}、{\zihao{4} size 4 (section headings)}.
\end{document}

Font size commands are "switches," not "scopes"—after writing \large, all subsequent text grows until the group ends. So always wrap them in braces: {\large large text}, so the following small text is not affected.

For Chinese documents, it is recommended to use \zihao{size} directly; a minus sign before the number means "small size," so \zihao{-4} is the famous "small 4"—the standard font size for Chinese university thesis bodies.

Three List Environments

Lists are the most commonly used "environments" in LaTeX (paired \begin and \end); the three environments correspond to three semantics.

EnvironmentPurposeLabel
itemizeParallel points, unorderedDots, dashes, etc.
enumerateOrdered steps1. 2. 3. numbering
descriptionTerm definitionsCustom term names

Example: The three list environments and nesting

\documentclass{ctexart}
\begin{document}

Unordered list itemize:
\begin{itemize}
\item First item
\item Second item
\begin{itemize}
\item Nested sub-item, symbol changes automatically
\item Another sub-item
\end{itemize}
\end{itemize}

Ordered list enumerate:
\begin{enumerate}
\item Install the distribution
\item Choose an editor
\item Compile your first document
\end{enumerate}

Description list description:
\begin{description}
\item[LaTeX] A typesetting system based on TeX
\item[Package] A plug-and-play functional extension
\end{description}

\end{document}

Unordered list itemize:

  • First item
  • Second item
    • Nested sub-item, symbol changes automatically
    • Another sub-item

Ordered list enumerate:

  1. Install the distribution
  2. Choose an editor
  3. Compile your first document

Description list description:

LaTeX A typesetting system based on TeX

Package A plug-and-play functional extension

Default lists require no extra setup; deep levels automatically indent and symbols change level by level (dots, dashes, stars...), up to four levels. Default list line spacing is loose; the enumitem package provides fine control for compact versions often needed in papers.

Example: Customizing lists with enumitem

\documentclass{ctexart}
\usepackage{enumitem} % Load package
\begin{document}
\begin{itemize}[label=\textsquare, noitemsep] % Square label + remove extra space between items
\item Compact unordered list
\end{itemize}

\begin{enumerate}[label=(\alph*)] % Numbering style changed to (a) (b) (c)
\item First point
\item Second point
\end{enumerate}
\end{document}
  • □ Compact unordered list
  1. (a) First point
  2. (b) Second point

Alignment

The body is justified by default, which is the standard for typesetting long documents; no setting is required. When local alignment changes are needed, use the three environments: center, flushleft, and flushright.

Example: Center and right alignment

\documentclass{ctexart}
\begin{document}
The body is justified by default, with the last line aligned to the left—this is the standard typographic practice.

\begin{center}
Centered text\\
The second line is also centered
\end{center}

\begin{flushright}
Right-aligned text\\
Signatures often use right alignment
\end{flushright}

\end{document}

UsageCharacteristicsApplicable Occasions
\begin{center}...\end{center}Environment form, adds vertical spacingIndependent centered paragraphs in the body
\centeringDeclarative command, no extra spacingInside float environments, see Chapter 8
\begin{flushright}...\end{flushright}Right-aligned environmentSignatures, dates

Summary

NeedCommandCommon Mistake
Bold / italic / monospace\textbf / \textit / \textttCommand only acts within braces
Emphasis\emphChinese is mapped to Kai typeface
Change font size\large ... or \zihao{n}Forgetting braces causes everything afterward to grow
Listsitemize / enumerate / description\begin and \end must be paired when nesting
Centeringcenter environment or \centeringDifferent inter-line behavior

Mathematical Formulas and Symbols

Mathematical typesetting is the crown jewel of LaTeX and the primary reason most people choose it. This chapter covers the foundations of mathematical formulas: inline and display formulas, subscripts and superscripts, fractions, roots, Greek letters, and common symbol tables.

Each "syntax \to effect" comparison in this document is rendered in real time; what you see in the document is what LaTeX produces.

Inline and Display Formulas

Formulas exist in only two forms: inline formulas embedded in sentences, wrapped in a pair of $; and display formulas centered on their own line, wrapped in \[ and \].

\documentclass{ctexart}
\usepackage{amsmath}
\usepackage{amssymb}
\begin{document}
The quadratic equation $ax^2 + bx + c = 0$ has the root formula
\[
x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a},
\]
where the discriminant $\Delta = b^2 - 4ac$ determines the number of roots.
\end{document}

Inline and display formula effect

FormSyntaxEffectWhen to Use
Inline formula$...$Same height as text, embedded in sentencesSimple formulas referenced by the sentence
Display formula\[...\]Independent line, centered, larger fontImportant or complex formulas

Two habits to avoid: first, using the old $$...$$ for display formulas, which has spacing flaws—unify to \[...\]; second, after a sentence is interrupted by a display formula, do not leave a blank line before the formula—the formula is still part of the sentence, not a new paragraph.

Subscripts and Superscripts

^ is superscript, _ is subscript, and both only act on the immediately following single character or brace group.

SyntaxRendered Result
x^2x2x^2
a_{ij}aija_{ij}
2^{n+1}2n+12^{n+1}
x_i^2xi2x_i^2
x^{i^2}xi2x^{i^2}
e^{-t}ete^{-t}

Compare the fourth and fifth lines: x_i^2 is "the square of the i-th x," while x^{i^2} is "x raised to the power of i2i^2"—braces determine the scope, and a tiny difference can be wildly wrong.

Subscripts and superscripts with more than one character must be enclosed in braces. \hat{x}10 will be typeset as x^10\hat{x}10 (x with a hat, followed directly by the number 10, not a superscript); the correct syntax is \hat{x}^{10}, producing x^10\hat{x}^{10}.

Fractions and Roots

\frac{numerator}{denominator} produces a fraction, \sqrt{radicand} produces a square root, and the n-th root is written as \sqrt[n]{...}.

SyntaxRendered Result
\frac{a+b}{c}a+bc\frac{a+b}{c}
\frac{1}{1+\frac{1}{x}}11+1x\frac{1}{1+\frac{1}{x}}
\sqrt{2}2\sqrt{2}
\sqrt[3]{x^2+1}x2+13\sqrt[3]{x^2+1}
(\frac{a}{b})(ab)(\frac{a}{b})
\left(\frac{a}{b}\right)(ab)\left(\frac{a}{b}\right)

The last pair is worth memorizing: ordinary parentheses do not grow with their content; \left( and \right) automatically adapt the parenthesis height to the content, essential for wrapping fractions and matrices.

Fractions in inline formulas are automatically compressed (denominator lowered, smaller font). If it is too small, replace \frac with \dfrac (display frac), and the fraction will retain its display size.

Greek Letters

Greek letters are written as "backslash + English name," with uppercase/lowercase controlled by the first letter of the command.

Lowercase Greek Letters

CommandEffectCommandEffect
\alphaα\alpha\betaβ\beta
\gammaγ\gamma\deltaδ\delta
\epsilonϵ\epsilon\varepsilonε\varepsilon
\thetaθ\theta\lambdaλ\lambda
\muμ\mu\piπ\pi
\sigmaσ\sigma\omegaω\omega
\phiϕ\phi\varphiφ\varphi

Uppercase Greek Letters

CommandEffectCommandEffect
\GammaΓ\Gamma\DeltaΔ\Delta
\SigmaΣ\Sigma\OmegaΩ\Omega

Note two things: uppercase commands only capitalize the first letter (\Sigma, not \SIGMA); \epsilon vs. \varepsilon and \phi vs. \varphi are two glyph variants of the same letter, each with its own mathematical convention. Keep consistent usage within a paper.

Quick Reference for Common Symbols

High-frequency symbols are grouped into three tables; the effect column is rendered in real time.

CommandEffectCommandEffect
\times×\times\div÷\div
\pm±\pm\mp\mp
\cdot\cdot\leq\leq
\geq\geq\neq\neq
\approx\approx\equiv\equiv
\ll\ll\gg\gg
CommandEffectCommandEffect
\in\in\notin\notin
\subset\subset\subseteq\subseteq
\cup\cup\cap\cap
\emptyset\emptyset\infty\infty
\forall\forall\exists\exists
\Rightarrow\Rightarrow\Leftrightarrow\Leftrightarrow
CommandEffectCommandEffect
\partial\partial\nabla\nabla
\to\to\mapsto\mapsto
\mathrm{d}xdx\mathrm{d}x\hat{x}x^\hat{x}
\bar{x}xˉ\bar{x}\vec{x}x\vec{x}

Large Operators: Sum, Integral, Limit

\sum, \int, and \lim are the three most commonly used large operators, used with subscripts and superscripts.

\sum_{i=1}^n i = \frac{n(n+1)}{2} \\[1em]
\int_{0}^{\infty} e^{-x^2} \mathrm{d}x = \frac{\sqrt{\pi}}{2} \\[1em]
\lim_{n\to\infty} \left(1+\frac{1}{n}\right)^n = e
i=1ni=n(n+1)20ex2dx=π2limn(1+1n)n=e\sum_{i=1}^n i = \frac{n(n+1)}{2} \\[1em] \int_{0}^{\infty} e^{-x^2} \mathrm{d}x = \frac{\sqrt{\pi}}{2} \\[1em] \lim_{n\to\infty} \left(1+\frac{1}{n}\right)^n = e

In display formulas, the limits of summation appear directly above and below the symbol; in inline formulas they are automatically compressed to the side. If you also want the "above/below" form inline, wrap it in \displaystyle.

Two Essential Packages: amsmath and amssymb

amsmath and amssymb are the "official extension libraries" for mathematical typesetting; it is recommended to load them before writing formulas.

PackageProvides
amsmathMore formula environments (align, etc., Chapter 7), \dfrac / \tfrac, equation numbering control
amssymbExtended mathematical symbols, such as \mathbb blackboard bold

Common font-effect commands in math also come from these two packages:

SyntaxEffect
\mathbb{R}R\mathbb{R}
\mathcal{F}F\mathcal{F}
\vec{v}v\vec{v}
\mathrm{e}^{\mathrm{i}\pi}eiπ\mathrm{e}^{\mathrm{i}\pi}

The last line is a typographical detail: the base of the natural logarithm e and the imaginary unit i, if written directly, are treated as variables and set in italics; wrapping them with \mathrm{} sets them upright, which conforms to publishing conventions. Do not include Chinese characters or full-width punctuation inside formulas. $\(\alpha\)+\(\beta\)$, with full-width plus signs and Unicode Greek letters typed from an input method, are wrong—formula content must be entered via commands, and Chinese explanations belong outside $.

Comprehensive Example: Compiling a Real Document

Put the contents of this chapter into a complete document and compile it:

\documentclass{ctexart}
\usepackage{amsmath} % Math formula enhancement package, standard for formula typesetting
\usepackage{amssymb}
\begin{document}

The quadratic equation $ax^2 + bx + c = 0$ has the root formula
\[
x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a},
\]
where the discriminant $\Delta = b^2 - 4ac$ determines the number of roots.

The most beautiful formula in mathematics is Euler's formula
\[
\mathrm{e}^{\mathrm{i}\pi} + 1 = 0,
\]
It connects the five most important constants.

\end{document}

Comprehensive example compiled effect

Summary

NeedSyntax
Inline formula$...$
Display formula\[...\]
Subscripts/superscripts\(\hat{x}\){10}、a_{ij} (multi-character requires braces)
Fraction / root\frac{a}{b}\sqrt[n]{x}
Adaptive parentheses\left( \right)
Large inline fraction\dfrac{a}{b}
Upright characters\mathrm{e}

Advanced Mathematical Formulas

The previous chapter solved single-line formulas; this chapter handles the "heavyweights": matrices, systems of equations, multi-line derivations, and formula numbering. They all come from the amsmath package—which is why every math document should have a line \usepackage{amsmath} in its preamble.

Matrices: The matrix Family

Matrices use environments: & separates columns, \\ starts a new line, and the environment name determines the outer bracket style.

EnvironmentOuter StyleTypical Use
matrixNo bracketsConcatenating data blocks
pmatrixParentheses ()Ordinary matrices
bmatrixSquare brackets []Coefficient matrices, linear algebra
BmatrixCurly braces {}Set notation
vmatrixSingle vertical bars | |Determinants
VmatrixDouble vertical bars || ||Norms

pmatrix (parenthesized matrix)

\[
\begin{pmatrix}
1 & 2 \\
3 & 4
\end{pmatrix}
\]
(1234)\begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}

bmatrix (bracketed matrix)

\[
\begin{bmatrix}
1 & 0 \\
0 & 1
\end{bmatrix}
\]
[1001]\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}

vmatrix (determinant)

\[
\begin{vmatrix}
a & b \\
c & d
\end{vmatrix}
= ad - bc
\]
abcd=adbc\begin{vmatrix} a & b \\ c & d \end{vmatrix} = ad - bc

Example: n-th Order Matrix with Ellipsis

\[
\begin{pmatrix}
a_{11} & \cdots & a_{1n} \\
\vdots & \ddots & \vdots \\
a_{n1} & \cdots & a_{nn}
\end{pmatrix}
\]
(a11a1nan1ann)\begin{pmatrix} a_{11} & \cdots & a_{1n} \\ \vdots & \ddots & \vdots \\ a_{n1} & \cdots & a_{nn} \end{pmatrix}

The three ellipsis commands have distinct roles: \cdots horizontal, \vdots vertical, \ddots diagonal. When matrix elements are numerous, always use ellipsis instead of typing dozens of elements. When a large matrix does not fit inline, use the smallmatrix environment, which compresses line spacing and font size.

Multi-line Derivations: The align Environment

align is the main environment for mathematical derivations: multi-line formulas are aligned at positions marked by &, and each line is automatically numbered.

Example: Two-line Derivation

\begin{align}
(a+b)^2 &= a^2 + 2ab + b^2 \\
&= a^2 + b^2 + 2ab
\end{align}
(a+b)2=a2+2ab+b2=a2+b2+2ab\begin{align} (a+b)^2 &= a^2 + 2ab + b^2 \\ &= a^2 + b^2 + 2ab \end{align}

There are only two rules: place & at the "alignment anchor" (usually before the equals sign), which splits the line into two columns; and \\ for line breaks. Each line automatically receives a number.

Example: Definite Integral Calculation

\begin{align}
\int_0^1 x^2 \,\mathrm{d}x
&= \left[ \frac{x^3}{3} \right]_0^1 \notag \\[2pt]
&= \frac{1}{3}
\end{align}
01x2dx=[x33]01=13\begin{align} \int_0^1 x^2 \,\mathrm{d}x &= \left[ \frac{x^3}{3} \right]_0^1 \notag \\[2pt] &= \frac{1}{3} \end{align}

Two new constructs appear here: \notag suppresses numbering for a line (use it for intermediate derivation steps that do not need numbers); [2pt] after \\ fine-tunes line spacing and can be omitted.

When no numbering is needed at all, use the starred align* environment—this follows the same logic as the section command \section*: the star means "unnumbered, not in the table of contents."

Systems of Equations and Piecewise Functions: The cases Environment

The cases environment specifically generates a grouped structure with a large brace on the left; it is the standard way to write systems of equations and piecewise functions.

Example: System of Two Linear Equations

\[
\begin{cases}
x + y = 5 \\
2x - y = 1
\end{cases}
\]
{x+y=52xy=1\begin{cases} x + y = 5 \\ 2x - y = 1 \end{cases}

Example: Piecewise Function

\[
f(x) =
\begin{cases}
-x, & x < 0 \\
x, & x \ge 0
\end{cases}
\]
f(x)={x,x<0x,x0f(x) = \begin{cases} -x, & x < 0 \\ x, & x \ge 0 \end{cases}

In piecewise functions, the role of & changes: it splits the line into two columns, "function value" and "condition," with the second column automatically right-aligned.

Formula Numbering and Referencing

Display formulas \[...\] are unnumbered; formulas that need to be referenced use the equation environment, which numbers them automatically.

Example: Numbering and Referencing

\documentclass{ctexart}
\usepackage{amsmath}
\begin{document}
From Eq.~\eqref{eq:pyth}, the hypotenuse of a right triangle satisfies
\begin{equation}\label{eq:pyth}
a^2 + b^2 = c^2,
\end{equation}
and the sum of the first $n$ terms of an arithmetic sequence is
\begin{equation}\label{eq:sum}
S_n = \frac{n(a_1 + a_n)}{2}.
\end{equation}
\end{document}

From Eq. (1), the hypotenuse of a right triangle satisfies

a2+b2=c2(1)a^2 + b^2 = c^2 \tag{1}

And the sum of the first nn terms of an arithmetic sequence is

Sn=n(a1+an)2(2)S_n = \frac{n(a_1 + a_n)}{2} \tag{2}

The two formulas are automatically numbered (1) and (2); when referencing, use \eqref{key} to get the number in parentheses.

Three steps to remember: equation handles numbering, \label{key} tags the formula, and \eqref{key} references it (automatically with parentheses). For label names, the suggestion is [type:content], such as eq:pyth, eq:sum—when there are many formulas, names like eq:3 reduce readability.

A reference showing ?? means the aux file has not been updated; compile again.

Breaking Long Formulas: The split Environment

When a single formula is too long for the page width, put it inside equation and use split to break it—the whole formula keeps a single number.

\begin{equation}
\begin{split}
\sum_{i=1}^n (x_i - \bar{x})(y_i - \bar{y})
&= \sum_{i=1}^n x_i y_i - n\bar{x}\bar{y} \\
&= \frac{1}{n}\sum_{i=1}^n x_i y_i - \bar{x}\bar{y}
\end{split}
\end{equation}
i=1n(xixˉ)(yiyˉ)=i=1nxiyinxˉyˉ=1ni=1nxiyixˉyˉ\begin{equation} \begin{split} \sum_{i=1}^n (x_i - \bar{x})(y_i - \bar{y}) &= \sum_{i=1}^n x_i y_i - n\bar{x}\bar{y} \\ &= \frac{1}{n}\sum_{i=1}^n x_i y_i - \bar{x}\bar{y} \end{split} \end{equation}

The difference between split and align: align is multiple formulas, each with its own number; split is one formula split into several lines, sharing one number. split must live inside equation (or \[...\]).

Common Formula Error Troubleshooting

Math-mode errors account for a large share of beginner errors. High-frequency errors are as follows:

Incorrect SyntaxProblemCorrect Syntax
Using \alpha directly in textMath commands can only be used in math modeα\alpha
a1+ba - 1 + bMissing content after _ or ^Add it: a1+b2a_1 + b^2
\dfracUsing \dfrac without loading amsmathAdd \usepackage{amsmath} in preamble
\a & b \\ c & dUsing & in an ordinary display formula& belongs only to matrix, align, etc.
Chinese explanations inside formulasFonts and line breaks become messed upPut explanations outside $ $, or use \text{...}
Forgetting \\ in alignMultiple lines squeezed into oneAdd \\ at the end of each line (except the last)

The \text{...} command is provided by the amsmath package. It is explained separately here: when a small amount of text needs to be embedded inside a mathematical formula (e.g., condition descriptions like "when (x>0)", physical units, etc.), use \text{} to wrap the text. This keeps the text upright and maintains reasonable character spacing.

Summary

NeedEnvironment / Command
Matrixpmatrix / bmatrix / vmatrix (& for columns, \\ for rows)
Multi-line derivation (numbered per line)align, starred version unnumbered
System of equations / piecewise functioncases
Single numbered formulaequation + \label
Reference formula number\eqref{key}
Long formula breaksplit inside equation

Figures and Tables

Figures and tables are the skeleton of a paper. This chapter covers four things: figure commands and floats, basic tables, academic three-line tables, and merging cells.

LaTeX's management philosophy for figures and tables is consistent with numbering: you only provide content and captions; position, numbering, and references are all automatic.

Graphics: The graphicx Package

Inserting graphics requires only two commands: load graphicx in the preamble, and use \includegraphics in the body to place the image file.

Common OptionMeaningExample
widthWidth, can use relative valueswidth=0.8\textwidth (80% of type width)
heightHeightheight=5cm
scaleScale factorscale=0.5
angleRotation angleangle=90

It is recommended to omit the file extension: write sin instead of sin.png. LaTeX will automatically search for formats supported by the current compiler (XeLaTeX supports PDF, PNG, JPG, etc.); changing format does not require modifying the source.

💡 When controlling image size, prefer the proportional value width=\textwidth over scale—the former ensures the image never exceeds the type area, while the latter may unexpectedly overflow under different font size settings.

Floats: The figure Environment

Images should not be placed directly in the text flow; the standard practice is to put them in the figure float environment.

Example: Standard Figure

\documentclass{ctexart}
\usepackage{graphicx} % Essential package for graphics
\begin{document}
The graph of the sine function $y = \sin x$ is shown in Figure~\ref{fig:sin}.

\begin{figure}[htbp] % Float environment; position parameters see table below
\centering % Image centered inside the float
\includegraphics[width=0.6\textwidth]{sin}
\caption{Sine curve} % Caption; number generated automatically
\label{fig:sin} % Label for \ref reference
\end{figure}
\end{document}
Sine curve

Figure 1: Sine curve

"Why did my image end up somewhere else?"—this is not a bug; it is the float mechanism at work: LaTeX chooses a position for each figure that does not create large gaps. When you really need to pin it down, use the float package's [H] parameter (uppercase, meaning here and do not move).

ParameterMeaningPriority Note
hhere, at the source positionOnly a suggestion; LaTeX will adjust if the page layout cannot accommodate
ttop, top of the current pageMost common choice in academic papers
bbottom, bottom of the current pageOften combined with t
pfloat page, independent float pageWhen there are many figures, they are automatically collected into an appendix page
! (e.g., [!h])Relax layout constraintsStack with strong requests

Basic Tables: The tabular Environment

The syntactic skeleton of a table is the same as a matrix: & separates columns, \\ starts a new line, and column formats are declared in the environment argument.

Example: Fully Bordered Table

\documentclass{ctexart}
\begin{document}
\begin{tabular}{|l|c|r|} % Column format: left/center/right alignment, vertical lines separate
\hline % Top horizontal line
Name & Age & Score \\ % & separates columns, \\ starts a new line
\hline
Zhang San & 20 & 92 \\
Li Si & 21 & 88 \\
\hline % Bottom horizontal line
\end{tabular}
\end{document}
NameAgeScoreZhang San2092Li Si2188\begin{array}{|l|c|r|} \hline \text{Name} & \text{Age} & \text{Score} \\ \hline \text{Zhang San} & 20 & 92 \\ \text{Li Si} & 21 & 88 \\ \hline \end{array}
Column Format SymbolMeaning
l/c/rLeft / center / right alignment for the column
|Draw a vertical line at this position
p{2cm}Fixed column width, with automatic line breaks inside cells

Academic Standard: booktabs Three-line Tables

Open any formal publication, and tables are "three horizontal lines, zero vertical lines"—this is called a three-line table, provided by the booktabs package.

Example: Three-line Table

\documentclass{ctexart}
\usepackage{booktabs} % Three-line table package
\begin{document}
\begin{tabular}{lccc} % Three-line tables use no vertical lines
\toprule % Top rule, thickest
Algorithm & Accuracy & Recall & F1 \\
\midrule % Middle rule, thinner
Model A & 0.91 & 0.88 & 0.89 \\
Model B & 0.93 & 0.90 & 0.91 \\
\bottomrule % Bottom rule, thickest
\end{tabular}
\end{document}
AlgorithmAccuracyRecallF1Model A0.910.880.89Model B0.930.900.91\begin{array}{lccc} \hline \text{Algorithm} & \text{Accuracy} & \text{Recall} & \text{F1} \\ \hline \text{Model A} & 0.91 & 0.88 & 0.89 \\ \text{Model B} & 0.93 & 0.90 & 0.91 \\ \hline \end{array}

💡 Journal and graduation thesis format guidelines almost always require three-line tables. Using | and \hline for fully bordered tables is fine for daily assignments, but please switch to booktabs before submission.

Merging Cells: multirow and multicolumn

Complex table headers need merging: horizontal merging uses \multicolumn (built into LaTeX), and vertical merging uses \multirow (requires loading the multirow package).

Example: Double-row Header

\documentclass{article}
\usepackage{booktabs}
\usepackage{multirow} % Merge cells vertically
\begin{document}
\begin{tabular}{lcc}
\toprule
\multirow{2}{*}{Dataset} & \multicolumn{2}{c}{Accuracy} \\
\cmidrule(lr){2-3} % Partial horizontal line for columns 2~3
& Training Set & Test Set \\
\midrule
MNIST & 0.99 & 0.98 \\
CIFAR-10 & 0.95 & 0.91 \\
\bottomrule
\end{tabular}
\end{document}

CommandSyntaxDescription
\multirow\multirow{rows}{width}{content}Span rows vertically; leave the corresponding positions empty in the spanned rows
\multicolumn\multicolumn{columns}{col-format}{content}Span columns horizontally; the cell's column format must be rewritten
\cmidrule\cmidrule(lr){2-3}Partial horizontal line; (lr) means a little space at both ends, more refined

Table Captions and Overall Floating

Tables also live in floats; the environment is table, and the rest of the routine is exactly the same as figure.

Example: Numbered Table

\begin{table}[htbp]
\centering
\caption{Experimental Result Comparison} % Caption (conventionally above the table)
\label{tab:result}
\begin{tabular}{lcc}
\toprule
Dataset & Training set & Test set \\
\midrule
MNIST & 0.99 & 0.98 \\
CIFAR-10 & 0.95 & 0.91 \\
\bottomrule
\end{tabular}
\end{table}

Table 1: Experimental Result Comparison

DatasetTraining SetTest SetMNIST0.990.98CIFAR-100.950.91\begin{array}{lcc} \hline \text{Dataset} & \text{Training Set} & \text{Test Set} \\ \hline \text{MNIST} & 0.99 & 0.98 \\ \text{CIFAR-10} & 0.95 & 0.91 \\ \hline \end{array}

Two unwritten conventions: table captions go above the table, and figure captions go below the image; use the prefixes tab: and fig: for labels, so the type is immediately recognizable when referenced. When a table is wider than the type area, two emergency solutions exist: wrap the entire tabular in \resizebox{\textwidth}{!}{...} for proportional scaling; or use the tabularx package to automatically distribute column widths.

Summary

NeedCommand / Environment
Graphics\includegraphics[width=0.8\textwidth]{filename}
Figure/table floatsfigure / table + [htbp] + \centering + \caption + \label
Table skeletontabular, & for columns, \\ for rows
Three-line tablebooktabs: \toprule \midrule \bottomrule
Merge cells\multirow, \multicolumn
Partial horizontal line\cmidrule(lr){2-3}

Cross-references and Bibliography Management

Two powerful automation tools for long documents: cross-references (sections, figures, tables, and formulas pointing to each other) and bibliography management (BibTeX). Their shared philosophy: numbering is always automatic; you are only responsible for choosing a "label name."

Labels and References: \label and \ref

Cross-referencing in three steps: use \label{label} at the referenced location, and use \ref{label} (or \pageref, \eqref) at the reference location to get the number.

CommandOutputTypical Use
\label{key}No output; tags the preceding objectImmediately after \section, \caption, or equation
\ref{key}Number (e.g., 3, 1.2)Section~\ref{sec:method}
\eqref{key}Number in parentheses (e.g., (1))Eq.~\eqref{eq:loss} (for formulas)
\pageref{key}Page numberSee page~\pageref{sec:method}

\label must immediately follow the referenced command and be written at the same environment level—\section{Method}\label{sec:method} is the correct posture; if you move \label to the next paragraph, it will refer to the wrong object. Formula \label must be written inside the equation environment.

Example: Cross-referencing Sections, Formulas, and Figures

\documentclass{ctexart}
\usepackage{amsmath, graphicx}
\begin{document}

\section{Method}\label{sec:method}
This section introduces the model structure. The loss function is Eq.~\eqref{eq:loss},
and the experimental analysis is in Section~\ref{sec:result}.

\begin{equation}\label{eq:loss}
L = \sum_{i=1}^n \left( y_i - \hat{y}_i \right)^2
\end{equation}

\section{Experimental Results}\label{sec:result}
The loss of the method (Section~\ref{sec:method}) is measured by Eq.~\eqref{eq:loss},
and the curve shape is shown in Figure~\ref{fig:sin}.

\begin{figure}[htbp]
\centering
\includegraphics[width=0.5\textwidth]{sin}
\caption{Sine curve}
\label{fig:sin}
\end{figure}

\end{document}

1 Method

This section introduces the model structure. The loss function is Eq. (1), and the experimental analysis is in Section 2.

L=i=1n(yiy^i)2(1)L = \sum_{i=1}^n \left( y_i - \hat{y}_i \right)^2 \tag{1}

2 Experimental Results

The loss of the method (Section 1) is measured by Eq. (1), and the curve shape is shown in Figure 1.

Sine curve

Figure 1: Sine curve

The compiled effect of cross-referencing sections, formulas, and figures: All references automatically obtained the correct numbers. No matter how many new sections or formulas are inserted later, numbering and references will update automatically—the ultimate cure for the "manually changing numbers until collapse" problem in Word.

Label naming suggests the "prefix:content" convention. Common prefix conventions are as follows.

PrefixObjectExample
sec:Section\label{sec:method}
fig:Figure\label{fig:sin}
tab:Table\label{tab:result}
eq:Formula\label{eq:loss}
chap:Chapter (report/book)\label{chap:intro}

After loading hyperref, all \ref, \cite, and \url automatically become clickable links, and a sidebar bookmark panel is generated in the PDF.

Example: Common hyperref Configuration

\usepackage[colorlinks=true, linkcolor=blue, % Body references: blue
citecolor=blue, urlcolor=blue]{hyperref}
% colorlinks=true marks links with color (default red boxes look bad)
% The three parameters control: internal references / citations / URL colors

\url{https://uniresearch.uniplore.com/} % URL typesetting: automatic line breaks, clickable

After configuration, references and URLs in the document become clickable hyperlinks.

For example: https://uniresearch.uniplore.com/

hyperref should almost always be the last package loaded in the preamble—it needs all other packages to be in place before it can correctly transform the document; loading it too early can cause mysterious conflicts.

Bibliographies: The BibTeX Workflow

The correct approach to bibliographies is not to hand-write a list at the end of the document, but to store bibliographic information in a .bib database, cite with \cite in the body, and let the BibTeX program automatically generate a formatted reference list.

First, see what a literature database looks like—each entry is an "item."

Example: refs.bib Literature Database

@article{alexnet2012, % Entry type: journal article
author = {Krizhevsky, Alex and Sutskever, Ilya and Hinton, Geoffrey E.},
title = {ImageNet Classification with Deep Convolutional Neural Networks},
journal = {Communications of the ACM},
year = {2017},
volume = {60},
pages = {84--90}
}

@book{goodfellow2016, % Entry type: book
author = {Goodfellow, Ian and Bengio, Yoshua and Courville, Aaron},
title = {Deep Learning},
publisher = {MIT Press},
year = {2016}
}

The first item in braces is the citation key (e.g., alexnet2012). In the body, \cite{alexnet2012} uses it to find this entry; the key name is arbitrary but must be unique throughout the document.

Entry TypeCorresponding LiteratureKey Fields
@articleJournal articleauthor, title, journal, year
@inproceedingsConference paperauthor, title, booktitle, year
@bookBookauthor/editor, title, publisher, year
@phdthesisPhD thesisauthor, title, school, year
@misc / @onlineWebpage, report, etc.title, url, note, year

There are only two commands on the body side, placed at the end of the document:

Example: Citing and Generating a Reference List

\documentclass{ctexart}
\begin{document}
The breakthrough in deep learning originated from AlexNet~\cite{alexnet2012},
and systematic textbooks can be referenced~\cite{goodfellow2016}.

\bibliographystyle{plain} % Bibliography style: plain numeric style
\bibliography{refs} % Bibliography database file (without .bib extension)
\end{document}

The breakthrough in deep learning originated from AlexNet[2], and systematic textbooks can be referenced[1].

References

[1] Goodfellow I, Bengio Y, Courville A. Deep Learning[M]. MIT Press, 2016.

[2] Krizhevsky A, Sutskever I, Hinton G E. ImageNet Classification with Deep Convolutional Neural Networks[J]. Communications of the ACM, 2017, 60: 84-90.

Citations automatically appear as [1], [2], and a reference list arranged in citation order is automatically generated at the end of the document—without you writing a single line of formatting.

Why Compile Four Times

With BibTeX added, the complete compilation becomes four steps, forming a pipeline between files.

StepCommandPurpose
1xelatex mainGenerate main.aux, recording which keys are cited in the body
2bibtex mainRead .aux and refs.bib, generate main.bbl reference list
3xelatex mainInsert the .bbl content into the document
4xelatex mainCitation numbers stabilize and display correctly

The reason references show "??" is hidden in this pipeline: BibTeX was not run, or it was run but not followed by two more compilations. Overleaf automatically runs all the steps; locally, latexmk -pdf main.tex is recommended to handle it in one go.

BibLaTeX: A More Modern Choice

BibTeX is an old library from 1985; its successor, biblatex (with the biber backend), is more worth knowing in Chinese contexts.

DimensionBibTeXbiblatex + biber
Birth time1985From 2009
Unicode / ChineseLimited supportNative UTF-8
Style customizationRequires writing .bst files, high thresholdLaTeX syntax, intuitive
Chinese national standardRequires configuration, cumbersomebiblatex-gb7714-2015 package directly supports it
Usage suggestionUse with old templates or when journals specifyPrefer for new projects and Chinese theses

Example: Basic biblatex Usage

\usepackage[backend=biber, style=numeric]{biblatex} % backend specifies biber
\addbibresource{refs.bib} % Note: include the .bib extension

\begin{document}
The breakthrough in deep learning originated from AlexNet~\cite{alexnet2012}.

\printbibliography[title=References] % Print bibliography at the end of the document
\end{document}

The breakthrough in deep learning originated from AlexNet[1].

References

[1] Krizhevsky A, Sutskever I, Hinton G E. ImageNet Classification with Deep Convolutional Neural Networks[J]. Communications of the ACM, 2017, 60: 84-90.

The command changes from bibtex to biber; the rest of the compilation pipeline is identical. When writing a Chinese graduation thesis, install the biblatex-gb7714-2015 package and change the style to gb7714-2015 to meet the national standard bibliographic format.

Summary

NeedCommand
Tag\label{prefix:name} (immediately after the referenced object)
Reference number / page / formula\ref, \pageref, \eqref
Hyperlinkshyperref (load last)
Cite literature\cite{key}, literature stored in .bib database
Generate reference listBibTeX: \bibliography; biblatex: \printbibliography
One-click compilationlatexmk -pdf main.tex

Common Packages and Tips

The previous chapters have already used quite a few packages; this chapter provides a systematic wrap-up: package quick reference, custom commands, code listings, multi-file projects, latexmk, and troubleshooting mindset. Mastering these "toolbox" topics evolves you from someone who can write LaTeX to someone who can manage LaTeX projects.

Common Package Quick Reference

Packages are loaded with \usepackage[options]{package-name}, all placed in the preamble.

PackagePurposeAppeared In
geometryPage margins and paperLaTeX Document Structure and Layout
fancyhdrHeaders and footersLaTeX Document Structure and Layout
amsmath / amssymbMath formula enhancement / extended symbolsLaTeX Math Formula Basics, LaTeX Advanced Math Formulas
graphicxGraphicsLaTeX Figures and Tables
booktabs / multirowThree-line tables / vertical cell mergingLaTeX Figures and Tables
enumitemList customizationLaTeX Text Formatting and Lists
xcolorColor definitionsIntroduced in this chapter
listingsCode listingsIntroduced in this chapter
hyperrefHyperlinks and bookmarksLaTeX Cross-references and Bibliography Management
biblatexBibliography (modern solution)LaTeX Cross-references and Bibliography Management
floatForced figure/table positioning [H]LaTeX Figures and Tables

When the local environment prompts File 'xxx.sty' not found, install it with tlmgr install xxx (TeX Live); MiKTeX will download automatically. Overleaf comes with almost all packages, so no such trouble.

Custom Commands: \newcommand

When you write the same content more than three times, it is time to define a command. \newcommand{command-name}[arg-count][definition].

Example: Three Types of Custom Commands

% No argument: shorten a long command
\newcommand{\R}{\mathbb{R}} % Writing $\R$ now produces $\mathbb{R}$

% One argument: encapsulate a fixed format
\newcommand{\email}[1]{\texttt{#1}} % #1 denotes the first argument

% Optional argument with default value: [arg-count][default]
\newcommand{\vecn}[2][n]{x_1, \dots, x_{#1}}
% Usage: $\vecn$ produces $x_1,\dots,x_n$
% $\vecn[5]$ produces $x_1,\dots,x_5$

\begin{document}
A function defined on $\R$, vectors $\vecn$ and $\vecn[5]$.
Contact email \email{uniresearch@email.uniplore.com}.
\end{document}

A function defined on R\mathbb{R}, vectors x1,,xnx_1, \dots, x_n and x1,,x5x_1, \dots, x_5.

Contact email: uniresearch@email.uniplore.com.

CommandPurposeNote
\newcommandDefine a new commandCommand name must not conflict with existing commands
\renewcommandRedefine an existing commandUse when customizing default styles; modify basic commands with care
\newenvironmentDefine a new environmentSame syntax; provide start and end code

Get to know the syntax for custom environments as well:

Example: Custom "Note" Environment

\newenvironment{note}
{\par\medskip\noindent\textbf{Note:}\itshape} % Start code
{\par\medskip} % End code

\begin{note}
This content will automatically start with "Note:" and be set in italics.
\end{note}

Note: This content will automatically start with "Note:" and be set in italics.

Code Listings: The listings Package

For posting code in technical documents, use the listings package. Language highlighting, line numbers, and borders are all automatic.

Example: Code Block with Highlighting and Line Numbers

\documentclass{ctexart}
\usepackage{listings} % Code listing package
\usepackage{xcolor} % Color support

\lstset{ % Global code style settings
basicstyle=\ttfamily\small, % Monospace font, slightly smaller size
keywordstyle=\color{blue}, % Keywords blue
commentstyle=\color{gray}, % Comments gray
stringstyle=\color{purple}, % Strings purple
numbers=left, % Line numbers on the left
numberstyle=\tiny\color{gray},
showstringspaces=false, % Do not show space markers inside strings
frame=single % Single-line frame
}

\begin{document}

\begin{lstlisting}[language=Python, caption=Computing the Fibonacci Sequence]
# Compute the n-th Fibonacci number (Chinese comment test)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)

print(fib(10)) # Output 55
\end{lstlisting}

\end{document}

Listing 1: Computing the Fibonacci Sequence

# Compute the n-th Fibonacci number (Chinese comment test)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)

print(fib(10)) # Output 55

lstlisting is a "verbatim environment": internal content is not interpreted by LaTeX at all; &, %, etc. do not need escaping. caption is also automatically numbered (Listing 1). Common language names include Python, C, Java, HTML, SQL, bash, etc.; without specifying language, plain text coloring is used.

UTF-8 Chinese support in listings depends on the compiler: Chinese comments work fine under XeLaTeX; older engines (latex/pdfLaTeX) will produce garbled text. For Chinese documents, always use XeLaTeX for compilation.

Multi-file Projects: \input and \include

Once a document exceeds a few hundred lines, it should be split into files—main.tex serves as the skeleton, and content is divided and conquered.

Example: main.tex Skeleton

\documentclass{ctexart}
\usepackage{amsmath, graphicx, booktabs, hyperref}

\begin{document}

\input{chapters/intro} % Introduction (filename without .tex)
\input{chapters/method} % Method
\input{chapters/result} % Experiments
\input{chapters/conclusion}% Conclusion

\bibliographystyle{plain}
\bibliography{refs}

\end{document}

The two commands look similar but have clear behavioral differences:

Comparison\input{file}\include{file}
Can be nestedYes (sub-files can further use input)No
Forces page breakNoEach file starts with a forced \clearpage
Works with \includeonlyNoYes; compiles only specified chapters (great for speed)
Suitable granularityArbitrary snippets (macros, figures, covers)Chapter-level large blocks

Common pitfall: \include forces a page break. Using it to stitch "several subsections on the same page" will cause mysterious page breaks—always use \input for small snippets.

latexmk: One-click Compilation

The four-step compilation pipeline from Chapter 9 is painful to type manually; latexmk automates it.

$ latexmk -xelatex main.tex # XeLaTeX engine, automatically runs all passes
$ latexmk -xelatex -C main.tex # Clean intermediate files together
$ latexmk -xelatex -c main.tex # Keep PDF, clean auxiliary files

latexmk automatically decides: if there is bibtex or changes in table-of-contents references, it compiles more times until all numbers stabilize. In the editor, configure the "build command" as latexmk -xelatex main.tex.

Troubleshooting Mindset

LaTeX error messages start with an exclamation mark and include a line number. The format is fixed; reading the first few lines is enough.

! Undefined control sequence.

l.42 \section{Method}

l.42 points to the offending line—in this example, line 42 misspelled \section as \secton. Fix this one place, and a chain of follow-up errors often disappears together.

Error MessageMeaningHandling
Undefined control sequenceCommand does not exist: spelling error or missing packageCheck spelling against the line number; confirm package is loaded
Missing $ insertedMath command appears in text modePut \alpha etc. inside $ $
File xxx not foundFile or package not foundCheck path; tlmgr install xxx
Runaway argumentEnvironment not closed (missing \end)Add \end{...} at the indicated line
LaTeX Error: Environment xxx undefinedUsed an undefined environmentCheck environment spelling and package
! Emergency stopCompilation completely stoppedScroll up in the log to find the first error
Reference undefined (warning)Reference is ??Compile again

Always fix only the first error in the log—the later errors are mostly chain reactions of the first. Recompile after fixing, which is much more reliable than changing ten places at once.

Summary

NeedSolution
Reduce repeated inputDefine commands and environments with \newcommand
Post codelistings + \lstset global styles
Split large documents\input (snippets) / \include (chapters)
One-click compilationlatexmk -xelatex
TroubleshootingRead the line number of the first ! error

Typesetting a Complete Paper

This chapter assembles all the knowledge from the previous ten chapters: using a multi-file project, typesetting a complete short paper with abstract, formulas, figures, tables, and references from scratch. It is recommended to follow along—watching is not the same as doing; walking through the whole process once makes LaTeX truly yours.

Project Structure

First plan the directory: skeleton separated from content, one file per chapter.

paper/
├── main.tex # Skeleton: preamble + assembling chapters in order
├── refs.bib # Reference database
├── figures/
│ └── fit.png # Figure
└── sections/
├── abstract.tex # Abstract
├── intro.tex # Introduction
├── method.tex # Method
├── result.tex # Experimental results
└── conclusion.tex# Conclusion

main.tex: Project Skeleton

The skeleton file does only three things: load packages, declare the title, and assemble the chapters in order.

Example: main.tex

\documentclass[12pt, a4paper]{ctexart}

% -------- Page layout and basic packages --------
\usepackage{geometry}
\geometry{margin=2.5cm}
\usepackage{amsmath, amssymb} % Math
\usepackage{graphicx} % Graphics
\usepackage{booktabs, multirow} % Three-line tables
\usepackage[colorlinks=true, linkcolor=blue,
citecolor=blue, urlcolor=blue]{hyperref}

% -------- Title information --------
\title{Research on Periodic Signal Fitting Based on Least Squares}
\author{UniResearch}
\date{\today}

\begin{document}

\maketitle

\input{sections/abstract} % Abstract
\input{sections/intro} % Introduction
\input{sections/method} % Method
\input{sections/result} % Experimental results
\input{sections/conclusion} % Conclusion

\bibliographystyle{plain}
\bibliography{refs} % References

\end{document}

Research on Periodic Signal Fitting Based on Least Squares

UniResearch

August 20, 2026

Abstract This paper studies parametric modeling of periodic signals. Based on the least squares criterion, the estimation procedure for the sinusoidal model y=Asin(ωx+φ)+cy = A\sin(\omega x + \varphi) + c is derived, and the method's effectiveness is verified on synthetic data. Experiments show that under low-noise conditions, the relative fitting error is below 1%.

Keywords: least squares; periodic signal; parameter estimation

Content of Each Chapter

Each file is just ordinary body text; the abstract and introduction are shown as examples.

Example: sections/abstract.tex

\begin{abstract}
This paper studies parametric modeling of periodic signals. Based on the least squares criterion, the estimation procedure for the sinusoidal model
$y = A\sin(\omega x + \varphi) + c$ is derived,
and the method's effectiveness is verified on synthetic data.

Experiments show that under low-noise conditions, the relative fitting error is below 1\%.

\medskip
\noindent\textbf{Keywords:} least squares; periodic signal; parameter estimation
\end{abstract}

Abstract This paper studies parametric modeling of periodic signals. Based on the least squares criterion, the estimation procedure for the sinusoidal model y=Asin(ωx+φ)+cy = A\sin(\omega x + \varphi) + c is derived, and the method's effectiveness is verified on synthetic data. Experiments show that under low-noise conditions, the relative fitting error is below 1%.

Keywords: least squares; periodic signal; parameter estimation

Example: sections/intro.tex

\section{Introduction}\label{sec:intro}
Periodic signals are widely found in communications, vibration analysis, and biomedical engineering;
parametric modeling of such signals is the common foundation for filtering, prediction, and compression~\cite{oppenheim1997}.
The classical least squares method provides a systematic solution framework for model parameter estimation~\cite{bjorck1996}.

The rest of this paper is organized as follows: Section~\ref{sec:method} establishes the model and gives the solution steps,
Section~\ref{sec:result} reports the experimental results, and Section~\ref{sec:conclusion} concludes.

1 Introduction

Periodic signals are widely found in communications, vibration analysis, and biomedical engineering; parametric modeling of such signals is the common foundation for filtering, prediction, and compression[2]. The classical least squares method provides a systematic solution framework for model parameter estimation[1].

The rest of this paper is organized as follows: Section 2 establishes the model and gives the solution steps, Section 3 reports the experimental results, and Section 4 concludes.

The method section holds formulas, and the experiment section holds figures and tables—you have already seen all the routines.

Example: sections/method.tex (formula part)

\section{Method}\label{sec:method}
Consider the following sinusoidal model:
\begin{equation}\label{eq:model}
y = A \sin(\omega x + \varphi) + c,
\end{equation}
where $A$ is amplitude, $\omega$ is angular frequency, $\varphi$ is initial phase, and $c$ is the DC component.

The goal of parameter estimation is to minimize the residual sum of squares
\begin{equation}\label{eq:loss}
S(A, \omega, \varphi, c)
= \sum_{i=1}^n \left( y_i - A \sin(\omega x_i + \varphi) - c \right)^2 .
\end{equation}
For fixed $\omega$, Eq.~\eqref{eq:loss} is a linear least squares problem with respect to the other parameters,
and can be solved directly by the normal equations.

2 Method

Consider the following sinusoidal model:

y=Asin(ωx+φ)+c(1)y = A \sin(\omega x + \varphi) + c \tag{1}

where AA is amplitude, ω\omega is angular frequency, φ\varphi is initial phase, and cc is the DC component.

The goal of parameter estimation is to minimize the residual sum of squares

S(A,ω,φ,c)=i=1n(yiAsin(ωxi+φ)c)2(2)S(A, \omega, \varphi, c) = \sum_{i=1}^n \left( y_i - A \sin(\omega x_i + \varphi) - c \right)^2 \tag{2}

For fixed ω\omega, Eq. (2) is a linear least squares problem with respect to the other parameters and can be solved directly by the normal equations.

Example: sections/result.tex (figures and tables part)

\section{Experimental Results}\label{sec:result}
Synthetic data were generated by sampling $n = 200$ points uniformly on $[0, 2\pi]$,
and Gaussian noise with standard deviation $0.05$ was added.
The comparison between the fitted curve and noisy sample points is shown in Figure~\ref{fig:fit},
and error metrics under different noise levels are shown in Table~\ref{tab:err}.

\begin{figure}[htbp]
\centering
\includegraphics[width=0.65\textwidth]{figures/fit}
\caption{Fitted curve (solid line) and noisy sample points (scatter)}
\label{fig:fit}
\end{figure}

\begin{table}[htbp]
\centering
\caption{Root Mean Square Error under Different Noise Levels}
\label{tab:err}
\begin{tabular}{lccc}
\toprule
Noise Std. Dev. & 0.01 & 0.05 & 0.10 \\
\midrule
RMSE & 0.011 & 0.053 & 0.104 \\
Relative Error & 1.1\% & 5.3\% & 10.4\% \\
\bottomrule
\end{tabular}
\end{table}
\end{section}

3 Experimental Results

Synthetic data were generated by sampling n=200n = 200 points uniformly on [0,2π][0, 2\pi], and Gaussian noise with standard deviation 0.05 was added. The comparison between the fitted curve and noisy sample points is shown in Figure 1; error metrics under different noise levels are shown in Table 1.

Fitted curve

Figure 1: Fitted curve (solid line) and noisy sample points (scatter)

Table 1: Root Mean Square Error under Different Noise Levels

Noise Std. Dev.0.010.050.10RMSE0.0110.0530.104Relative Error1.1%5.3%10.4%\begin{array}{lccc} \hline \text{Noise Std. Dev.} & 0.01 & 0.05 & 0.10 \\ \hline \text{RMSE} & 0.011 & 0.053 & 0.104 \\ \text{Relative Error} & 1.1\% & 5.3\% & 10.4\% \\ \hline \end{array}

refs.bib contains two bibliographic entries, and the body cites \cite{oppenheim1997} and \cite{bjorck1996} (full syntax in Chapter 9).

Compilation and Output

For a multi-file project, only main.tex needs to be compiled; \input will expand automatically. The full workflow with bibliography:

$ cd paper
$ latexmk -xelatex main.tex # One-click completion (recommended)
# Or manually four steps: xelatex -> bibtex -> xelatex -> xelatex

First-page output (title area, abstract and keywords, introduction citation numbers):

\title{Research on Periodic Signal Fitting Based on Least Squares}
\author{UniResearch}
\date{\today}

\begin{abstract}
This paper studies parametric modeling of periodic signals. Based on the least squares criterion, the estimation procedure for the sinusoidal model
$y = A\sin(\omega x + \varphi) + c$ is derived,
and the method's effectiveness is verified on synthetic data.

Experiments show that under low-noise conditions, the relative fitting error is below 1\%.

\medskip
\noindent\textbf{Keywords:} least squares; periodic signal; parameter estimation
\end{abstract}

\section{Introduction}\label{sec:intro}
Periodic signals are widely found in communications, vibration analysis, and biomedical engineering;
parametric modeling of such signals is the common foundation for filtering, prediction, and compression~\cite{oppenheim1997}.
The classical least squares method provides a systematic solution framework for model parameter estimation~\cite{bjorck1996}.

The rest of this paper is organized as follows: Section~\ref{sec:method} establishes the model and gives the solution steps,
Section~\ref{sec:result} reports the experimental results, and Section~\ref{sec:conclusion} concludes.

Research on Periodic Signal Fitting Based on Least Squares

UniResearch

August 20, 2026

Abstract

This paper studies parametric modeling of periodic signals. Based on the least squares criterion, the estimation procedure for the sinusoidal model y=Asin(ωx+φ)+cy = A\sin(\omega x + \varphi) + c is derived, and the method's effectiveness is verified on synthetic data. Experiments show that under low-noise conditions, the relative fitting error is below 1%.

Keywords: least squares; periodic signal; parameter estimation

1 Introduction

Periodic signals are widely found in communications, vibration analysis, and biomedical engineering; parametric modeling of such signals is the common foundation for filtering, prediction, and compression[2]. The classical least squares method provides a systematic solution framework for model parameter estimation[1].

The rest of this paper is organized as follows: Section 2 establishes the model and gives the solution steps, Section 3 reports the experimental results, and Section 4 concludes.

Second-page output (formula numbering and references, floating figure, three-line table, conclusion, and references):

\section{Method}\label{sec:method}
Consider the following sinusoidal model:
\begin{equation}\label{eq:model}
y = A \sin(\omega x + \varphi) + c,
\end{equation}
where $A$ is amplitude, $\omega$ is angular frequency, $\varphi$ is initial phase, and $c$ is the DC component.

The goal of parameter estimation is to minimize the residual sum of squares
\begin{equation}\label{eq:loss}
S(A, \omega, \varphi, c)
= \sum_{i=1}^n \left( y_i - A \sin(\omega x_i + \varphi) - c \right)^2 .
\end{equation}
For fixed $\omega$, Eq.~\eqref{eq:loss} is a linear least squares problem with respect to the other parameters,
and can be solved directly by the normal equations; $\omega$ is determined by grid search over the interval $[\omega_{\min}, \omega_{\max}]$,
and the parameter combination that minimizes $S$ is selected.

\section{Experimental Results}\label{sec:result}
Synthetic data were generated by sampling $n = 200$ points uniformly on $[0, 2\pi]$,
and Gaussian noise with standard deviation $0.05$ was added.
The comparison between the fitted curve and noisy sample points is shown in Figure~\ref{fig:fit},
and error metrics under different noise levels are shown in Table~\ref{tab:err}.

\begin{figure}[htbp]
\centering
\includegraphics[width=0.65\textwidth]{figures/fit}
\caption{Fitted curve (solid line) and noisy sample points (scatter)}
\label{fig:fit}
\end{figure}

\begin{table}[htbp]
\centering
\caption{Root Mean Square Error under Different Noise Levels}
\label{tab:err}
\begin{tabular}{lccc}
\toprule
Noise Std. Dev. & 0.01 & 0.05 & 0.10 \\
\midrule
RMSE & 0.011 & 0.053 & 0.104 \\
Relative Error & 1.1\% & 5.3\% & 10.4\% \\
\bottomrule
\end{tabular}
\end{table}

\section{Conclusion}\label{sec:conclusion}
This paper decomposes sinusoidal fitting into two steps, "grid search + linear least squares,"
with a simple process and stable solution.
Future work will extend the method to multi-component harmonic signals,
and study automatic estimation of frequency initial values.

\begin{thebibliography}{9}
\bibitem{bjorck1996}
Åke Björck. \textit{Numerical Methods for Least Squares Problems}. SIAM, 1996.
\bibitem{oppenheim1997}
Alan V. Oppenheim and Alan S. Willsky. \textit{Signals and Systems}. Prentice Hall, 2 edition, 1997.
\end{thebibliography}

2 Method

Consider the following sinusoidal model:

y=Asin(ωx+φ)+c(1)y = A \sin(\omega x + \varphi) + c \tag{1}

where AA is amplitude, ω\omega is angular frequency, φ\varphi is initial phase, and cc is the DC component.

The goal of parameter estimation is to minimize the residual sum of squares

S(A,ω,φ,c)=i=1n(yiAsin(ωxi+φ)c)2(2)S(A, \omega, \varphi, c) = \sum_{i=1}^n \left( y_i - A \sin(\omega x_i + \varphi) - c \right)^2 \tag{2}

For fixed ω\omega, Eq. (2) is a linear least squares problem with respect to the other parameters and can be solved directly by the normal equations; ω\omega is determined by grid search over the interval [ω_min, ω_max], and the parameter combination that minimizes SS is selected.

3 Experimental Results

Synthetic data were generated by sampling n=200n = 200 points uniformly on [0,2π][0, 2\pi], and Gaussian noise with standard deviation 0.05 was added. The comparison between the fitted curve and noisy sample points is shown in Figure 1; error metrics under different noise levels are shown in Table 1.

Fitted curve

Figure 1: Fitted curve (solid line) and noisy sample points (scatter)

Table 1: Root Mean Square Error under Different Noise Levels

Noise Std. Dev.0.010.050.10RMSE0.0110.0530.104Relative Error1.1%5.3%10.4%\begin{array}{lccc} \hline \text{Noise Std. Dev.} & 0.01 & 0.05 & 0.10 \\ \hline \text{RMSE} & 0.011 & 0.053 & 0.104 \\ \text{Relative Error} & 1.1\% & 5.3\% & 10.4\% \\ \hline \end{array}

4 Conclusion

This paper decomposes sinusoidal fitting into two steps, "grid search + linear least squares," with a simple process and stable solution. Future work will extend the method to multi-component harmonic signals and study automatic estimation of frequency initial values.

References

[1] Åke Björck. Numerical Methods for Least Squares Problems. SIAM, 1996.

[2] Alan V. Oppenheim and Alan S. Willsky. Signals and Systems. Prentice Hall, 2 edition, 1997.

Check a few "automation traces": the citation numbers [1] and [2] in the introduction correspond one-to-one with the references at the end; figures and tables each have their own numbers, and the body references "Figure 1" and "Table 1" are all correct; formulas (1) and (2) are referenced by \eqref in parenthesized form.

Modify any reference or number and rerun latexmk; all numbers update automatically—this is the document that ten chapters of content bought you: "never manually check numbers again."

Real World: Start from a Template

In real paper writing, you should not build the skeleton from scratch—journals and schools provide ready-made templates.

Template SourceWhere to FindCharacteristics
Overleaf template libraryOverleaf → TemplatesThousands of thesis, journal, and poster templates, open with one click
Journal official websiteJournal Author Guidelines pageSubmission-specified format; always follow this
School thesis templateSchool library / GitHub search "[school name] + thesis"Meets school format review
GitHubSearch awesome-latex and similar collectionsCommunity-maintained templates and resource summaries

The one-sentence golden rule: Only fill in the placeholders, never touch the template structure. Those preamble settings in the template that you do not understand were tuned by others; deleting or changing one place may break the whole document.

Summary

AspectPractice in This Chapter
Project organizationmain.tex skeleton + sections/ chapters + figures/ images
Preamblegeometry, amsmath, graphicx, booktabs, hyperref
Body elementsAbstract, sections, formulas, figures/tables, cross-references, bibliography
Compilationlatexmk -xelatex in one step
Efficiency tipUse official templates for real submissions; only fill content, do not change structure