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
| Feature | LaTeX | Microsoft Word |
|---|---|---|
| Typesetting quality | Professional-grade, especially for complex formulas and long documents. | Suitable for simple documents; complex layouts require manual adjustment. |
| Learning curve | Requires learning basic syntax; steeper at first. | WYSIWYG, easy to get started. |
| Automation | Automatic numbering, cross-references, table of contents, etc. | Manual numbering and formatting required. |
| Math formula support | Powerful formula typesetting, supporting complex symbols and structures. | Limited formula editor; complex formulas are difficult. |
| Cross-platform support | Fully cross-platform, consistent document rendering across systems. | Good cross-platform support, but formatting may vary by version. |
| Document structure | Content and formatting separated, easier maintenance and collaboration. | Content and formatting mixed, harder to maintain long documents. |
| Extensibility | Extend functionality via packages, support custom commands and environments. | Feature extensions rely on plugins, less flexible. |
LaTeX Workflow
- Write LaTeX source code: Use a plain text editor to write
.texfiles containing document structure, text, and commands. - Compile LaTeX source code: Use a LaTeX compiler (such as pdflatex, xelatex, lualatex, etc.) to compile the source code into a PDF file.
- Preview the PDF file: Use a PDF reader to preview the compiled PDF file; the content is automatically typeset according to the source code.
- 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:
article: short articles, conference papersreport: course reports, theses, supports chaptersbook: 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}

| Command | Purpose | Common Usage |
|---|---|---|
\title{...} | Declare title | Manual line breaks with \\ allowed in title |
\author{...} | Declare author | Zhang San \and Li Si; \thanks can add affiliation footnotes |
\date{...} | Declare date | \today for today; fixed date handwritten; {} to hide |
\maketitle | Render title area | Place 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.
| Command | Level | Applicable 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
.auxfile 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.
| Option | Meaning | Example |
|---|---|---|
| margin | Uniform margin on all sides | margin=2.5cm |
| top / bottom / left / right | Control one side individually | left=3cm,right=3cm |
| a4paper / a5paper / letterpaper | Paper size | a4paper |
| landscape | Landscape page | For wide slides or wide tables |
| textwidth / textheight | Directly specify type area width/height | textwidth=15cm |
For domestic theses, the "symmetric odd-even binding" is common: add
bindingoffset=1cmto 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.
| Command | Controlled 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}

\markrightand\leftmarkare 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.
| Command | Purpose | Usage Suggestion |
|---|---|---|
\newpage | End current page, continue from new page | Recommended for daily use |
\clearpage | New page and first output all pending floats | Safer at end of chapters or document |
\linebreak | Force line break here with justified alignment | Use sparingly; let LaTeX break lines automatically |
\pagebreak | Suggest a page break here (contrast with \nopagebreak) | Use sparingly |
Do not frequently use
\newpageto "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
| Function | Command / Package | Location |
|---|---|---|
| Title area | \title / \author / \maketitle | Declared in preamble, rendered in body |
| Sections | \section / \subsection / \subsubsection | Body |
| Footnotes | \footnote{...} | Body (usually right after text) |
| Table of contents | \tableofcontents | After preamble, before body |
| Page margins | geometry package | Preamble |
| Headers/footers | fancyhdr package | Preamble |
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.
| Effect | Command | Description |
|---|---|---|
| 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 large | Command |
|---|---|
| 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.
| Environment | Purpose | Label |
|---|---|---|
| itemize | Parallel points, unordered | Dots, dashes, etc. |
| enumerate | Ordered steps | 1. 2. 3. numbering |
| description | Term definitions | Custom 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:
- Install the distribution
- Choose an editor
- 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
- (a) First point
- (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}

| Usage | Characteristics | Applicable Occasions |
|---|---|---|
\begin{center}...\end{center} | Environment form, adds vertical spacing | Independent centered paragraphs in the body |
\centering | Declarative command, no extra spacing | Inside float environments, see Chapter 8 |
\begin{flushright}...\end{flushright} | Right-aligned environment | Signatures, dates |
Summary
| Need | Command | Common Mistake |
|---|---|---|
| Bold / italic / monospace | \textbf / \textit / \texttt | Command only acts within braces |
| Emphasis | \emph | Chinese is mapped to Kai typeface |
| Change font size | \large ... or \zihao{n} | Forgetting braces causes everything afterward to grow |
| Lists | itemize / enumerate / description | \begin and \end must be paired when nesting |
| Centering | center environment or \centering | Different 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 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}

| Form | Syntax | Effect | When to Use |
|---|---|---|---|
| Inline formula | $...$ | Same height as text, embedded in sentences | Simple formulas referenced by the sentence |
| Display formula | \[...\] | Independent line, centered, larger font | Important 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.
| Syntax | Rendered Result |
|---|---|
x^2 | |
a_{ij} | |
2^{n+1} | |
x_i^2 | |
x^{i^2} | |
e^{-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 "—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}10will be typeset as (x with a hat, followed directly by the number 10, not a superscript); the correct syntax is\hat{x}^{10}, producing .
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]{...}.
| Syntax | Rendered Result |
|---|---|
\frac{a+b}{c} | |
\frac{1}{1+\frac{1}{x}} | |
\sqrt{2} | |
\sqrt[3]{x^2+1} | |
(\frac{a}{b}) | |
\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
| Command | Effect | Command | Effect |
|---|---|---|---|
\alpha | \beta | ||
\gamma | \delta | ||
\epsilon | \varepsilon | ||
\theta | \lambda | ||
\mu | \pi | ||
\sigma | \omega | ||
\phi | \varphi |
Uppercase Greek Letters
| Command | Effect | Command | Effect |
|---|---|---|---|
\Gamma | \Delta | ||
\Sigma | \Omega |
Note two things: uppercase commands only capitalize the first letter (
\Sigma, not\SIGMA);\epsilonvs.\varepsilonand\phivs.\varphiare 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.
| Command | Effect | Command | Effect |
|---|---|---|---|
\times | \div | ||
\pm | \mp | ||
\cdot | \leq | ||
\geq | \neq | ||
\approx | \equiv | ||
\ll | \gg |
| Command | Effect | Command | Effect |
|---|---|---|---|
\in | \notin | ||
\subset | \subseteq | ||
\cup | \cap | ||
\emptyset | \infty | ||
\forall | \exists | ||
\Rightarrow | \Leftrightarrow |
| Command | Effect | Command | Effect |
|---|---|---|---|
\partial | \nabla | ||
\to | \mapsto | ||
\mathrm{d}x | \hat{x} | ||
\bar{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
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.
| Package | Provides |
|---|---|
| amsmath | More formula environments (align, etc., Chapter 7), \dfrac / \tfrac, equation numbering control |
| amssymb | Extended mathematical symbols, such as \mathbb blackboard bold |
Common font-effect commands in math also come from these two packages:
| Syntax | Effect |
|---|---|
\mathbb{R} | |
\mathcal{F} | |
\vec{v} | |
\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}

Summary
| Need | Syntax |
|---|---|
| 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.
| Environment | Outer Style | Typical Use |
|---|---|---|
matrix | No brackets | Concatenating data blocks |
pmatrix | Parentheses () | Ordinary matrices |
bmatrix | Square brackets [] | Coefficient matrices, linear algebra |
Bmatrix | Curly braces {} | Set notation |
vmatrix | Single vertical bars | | | Determinants |
Vmatrix | Double vertical bars || || | Norms |
pmatrix (parenthesized matrix)
\[
\begin{pmatrix}
1 & 2 \\
3 & 4
\end{pmatrix}
\]
bmatrix (bracketed matrix)
\[
\begin{bmatrix}
1 & 0 \\
0 & 1
\end{bmatrix}
\]
vmatrix (determinant)
\[
\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}
\]
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}
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}
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}
\]
Example: Piecewise Function
\[
f(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
And the sum of the first terms of an arithmetic sequence is
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}
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 Syntax | Problem | Correct Syntax |
|---|---|---|
Using \alpha directly in text | Math commands can only be used in math mode | |
Missing content after _ or ^ | Add it: | |
\dfrac | Using \dfrac without loading amsmath | Add \usepackage{amsmath} in preamble |
\a & b \\ c & d | Using & in an ordinary display formula | & belongs only to matrix, align, etc. |
| Chinese explanations inside formulas | Fonts and line breaks become messed up | Put explanations outside $ $, or use \text{...} |
Forgetting \\ in align | Multiple lines squeezed into one | Add \\ 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
| Need | Environment / Command |
|---|---|
| Matrix | pmatrix / bmatrix / vmatrix (& for columns, \\ for rows) |
| Multi-line derivation (numbered per line) | align, starred version unnumbered |
| System of equations / piecewise function | cases |
| Single numbered formula | equation + \label |
| Reference formula number | \eqref{key} |
| Long formula break | split 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 Option | Meaning | Example |
|---|---|---|
| width | Width, can use relative values | width=0.8\textwidth (80% of type width) |
| height | Height | height=5cm |
| scale | Scale factor | scale=0.5 |
| angle | Rotation angle | angle=90 |
It is recommended to omit the file extension: write
sininstead ofsin.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=\textwidthoverscale—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}

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).
| Parameter | Meaning | Priority Note |
|---|---|---|
| h | here, at the source position | Only a suggestion; LaTeX will adjust if the page layout cannot accommodate |
| t | top, top of the current page | Most common choice in academic papers |
| b | bottom, bottom of the current page | Often combined with t |
| p | float page, independent float page | When there are many figures, they are automatically collected into an appendix page |
| ! (e.g., [!h]) | Relax layout constraints | Stack 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}
| Column Format Symbol | Meaning |
|---|---|
| l/c/r | Left / 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}
💡 Journal and graduation thesis format guidelines almost always require three-line tables. Using
|and\hlinefor fully bordered tables is fine for daily assignments, but please switch tobooktabsbefore 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}

| Command | Syntax | Description |
|---|---|---|
\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
Two unwritten conventions: table captions go above the table, and figure captions go below the image; use the prefixes
tab:andfig: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 entiretabularin\resizebox{\textwidth}{!}{...}for proportional scaling; or use thetabularxpackage to automatically distribute column widths.
Summary
| Need | Command / Environment |
|---|---|
| Graphics | \includegraphics[width=0.8\textwidth]{filename} |
| Figure/table floats | figure / table + [htbp] + \centering + \caption + \label |
| Table skeleton | tabular, & for columns, \\ for rows |
| Three-line table | booktabs: \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.
| Command | Output | Typical Use |
|---|---|---|
\label{key} | No output; tags the preceding object | Immediately 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 number | See page~\pageref{sec:method} |
\labelmust 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\labelto the next paragraph, it will refer to the wrong object. Formula\labelmust 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.
2 Experimental Results
The loss of the method (Section 1) is measured by Eq. (1), and the curve shape is shown in Figure 1.

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.
| Prefix | Object | Example |
|---|---|---|
| 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} |
Hyperlinks: The hyperref Package
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/
hyperrefshould 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 Type | Corresponding Literature | Key Fields |
|---|---|---|
@article | Journal article | author, title, journal, year |
@inproceedings | Conference paper | author, title, booktitle, year |
@book | Book | author/editor, title, publisher, year |
@phdthesis | PhD thesis | author, title, school, year |
@misc / @online | Webpage, 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.
| Step | Command | Purpose |
|---|---|---|
| 1 | xelatex main | Generate main.aux, recording which keys are cited in the body |
| 2 | bibtex main | Read .aux and refs.bib, generate main.bbl reference list |
| 3 | xelatex main | Insert the .bbl content into the document |
| 4 | xelatex main | Citation 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.
| Dimension | BibTeX | biblatex + biber |
|---|---|---|
| Birth time | 1985 | From 2009 |
| Unicode / Chinese | Limited support | Native UTF-8 |
| Style customization | Requires writing .bst files, high threshold | LaTeX syntax, intuitive |
| Chinese national standard | Requires configuration, cumbersome | biblatex-gb7714-2015 package directly supports it |
| Usage suggestion | Use with old templates or when journals specify | Prefer 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
| Need | Command |
|---|---|
| Tag | \label{prefix:name} (immediately after the referenced object) |
| Reference number / page / formula | \ref, \pageref, \eqref |
| Hyperlinks | hyperref (load last) |
| Cite literature | \cite{key}, literature stored in .bib database |
| Generate reference list | BibTeX: \bibliography; biblatex: \printbibliography |
| One-click compilation | latexmk -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.
| Package | Purpose | Appeared In |
|---|---|---|
| geometry | Page margins and paper | LaTeX Document Structure and Layout |
| fancyhdr | Headers and footers | LaTeX Document Structure and Layout |
| amsmath / amssymb | Math formula enhancement / extended symbols | LaTeX Math Formula Basics, LaTeX Advanced Math Formulas |
| graphicx | Graphics | LaTeX Figures and Tables |
| booktabs / multirow | Three-line tables / vertical cell merging | LaTeX Figures and Tables |
| enumitem | List customization | LaTeX Text Formatting and Lists |
| xcolor | Color definitions | Introduced in this chapter |
| listings | Code listings | Introduced in this chapter |
| hyperref | Hyperlinks and bookmarks | LaTeX Cross-references and Bibliography Management |
| biblatex | Bibliography (modern solution) | LaTeX Cross-references and Bibliography Management |
| float | Forced figure/table positioning [H] | LaTeX Figures and Tables |
When the local environment prompts
File 'xxx.sty' not found, install it withtlmgr 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 , vectors and .
Contact email: uniresearch@email.uniplore.com.
| Command | Purpose | Note |
|---|---|---|
\newcommand | Define a new command | Command name must not conflict with existing commands |
\renewcommand | Redefine an existing command | Use when customizing default styles; modify basic commands with care |
\newenvironment | Define a new environment | Same 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
listingsdepends 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 nested | Yes (sub-files can further use input) | No |
| Forces page break | No | Each file starts with a forced \clearpage |
Works with \includeonly | No | Yes; compiles only specified chapters (great for speed) |
| Suitable granularity | Arbitrary snippets (macros, figures, covers) | Chapter-level large blocks |
Common pitfall:
\includeforces a page break. Using it to stitch "several subsections on the same page" will cause mysterious page breaks—always use\inputfor 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.42points to the offending line—in this example, line 42 misspelled\sectionas\secton. Fix this one place, and a chain of follow-up errors often disappears together.
| Error Message | Meaning | Handling |
|---|---|---|
| Undefined control sequence | Command does not exist: spelling error or missing package | Check spelling against the line number; confirm package is loaded |
| Missing $ inserted | Math command appears in text mode | Put \alpha etc. inside $ $ |
File xxx not found | File or package not found | Check path; tlmgr install xxx |
| Runaway argument | Environment not closed (missing \end) | Add \end{...} at the indicated line |
| LaTeX Error: Environment xxx undefined | Used an undefined environment | Check environment spelling and package |
| ! Emergency stop | Compilation completely stopped | Scroll 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
| Need | Solution |
|---|---|
| Reduce repeated input | Define commands and environments with \newcommand |
| Post code | listings + \lstset global styles |
| Split large documents | \input (snippets) / \include (chapters) |
| One-click compilation | latexmk -xelatex |
| Troubleshooting | Read 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 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 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:
where is amplitude, is angular frequency, is initial phase, and is the DC component.
The goal of parameter estimation is to minimize the residual sum of squares
For fixed , 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 points uniformly on , 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.

Figure 1: Fitted curve (solid line) and noisy sample points (scatter)
Table 1: Root Mean Square Error under Different Noise Levels
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 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:
where is amplitude, is angular frequency, is initial phase, and is the DC component.
The goal of parameter estimation is to minimize the residual sum of squares
For fixed , Eq. (2) is a linear least squares problem with respect to the other parameters and can be solved directly by the normal equations; is determined by grid search over the interval [ω_min, ω_max], and the parameter combination that minimizes is selected.
3 Experimental Results
Synthetic data were generated by sampling points uniformly on , 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.

Figure 1: Fitted curve (solid line) and noisy sample points (scatter)
Table 1: Root Mean Square Error under Different Noise Levels
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 Source | Where to Find | Characteristics |
|---|---|---|
| Overleaf template library | Overleaf → Templates | Thousands of thesis, journal, and poster templates, open with one click |
| Journal official website | Journal Author Guidelines page | Submission-specified format; always follow this |
| School thesis template | School library / GitHub search "[school name] + thesis" | Meets school format review |
| GitHub | Search awesome-latex and similar collections | Community-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
| Aspect | Practice in This Chapter |
|---|---|
| Project organization | main.tex skeleton + sections/ chapters + figures/ images |
| Preamble | geometry, amsmath, graphicx, booktabs, hyperref |
| Body elements | Abstract, sections, formulas, figures/tables, cross-references, bibliography |
| Compilation | latexmk -xelatex in one step |
| Efficiency tip | Use official templates for real submissions; only fill content, do not change structure |