[Tips and Tricks] How to Create and Typeset Piecewise Functions In LaTex

Learn how you can write a piecewise function in LaTex using the `cases` environment under `amsmath` package.

Piecewise functions, also known as “cases” or “if-then” functions, are functions commonly used in expressing complex relationships or representing solutions to certain types of problems.

In this article, we’re going to show you how to make a piecewise function in LaTex with the help of the cases environment provided by the amsmath package.

Create piecewise functions using the `cases` environment

The amsmath package adapts most of the mathematical features in LaTex and is highly recommended to those who are serious about mathematical typesetting in LaTex. It provides additional math formatting and layout options.

One of the useful features of the amsmath package is it provides an environment for creating piecewise functions using the cases environment. To use the amsmath package in your environment, you can include the following in the preamble of your LaTeX document:

\usepackage{amsmath}

To use the cases environment, we enclose the function definition within a \begin{cases} and \end{cases} block, and we specify each case using the following syntax:

f(x) = 
\begin{cases}
expression & \text{if condition} \\
expression & \text{if condition} \\
expression & \text{if condition} \\
...
\end{cases}

The example below is how we write the absolute value function in a piecewise-defined form.

The absolute value function can be defined as a piecewise function.

We can simply produce that output with the code below. Note that the use of \\ is straightforward.

\documentclass{article}
\usepackage{amsmath}

\begin{document}

\begin{equation}
|x| =  \begin{cases}
             x & \text{if } x > 0 \\
             0 & \text{if } x = 0 \\
            -x & \text{if } x < 0
        \end{cases}
\end{equation}

\end{document}

Create piecewise functions using the `array` environment

The array environment from the amsmath package is another tool that we can use when writing mathematical content in LaTex. Imagine wanting to output the following:

As complicated as it may look, this can be done with the following code:

\documentclass{article}
\usepackage{amsmath}

\begin{document}

\begin{equation}
Y(i,k) = 
\left\{
    \begin{array}{lr}
        ||R_{k}-R_{i}||^{2}     & \text{, if } i \neq k\\
        ||\triangle_{i}||^{2}   & \text{, if } i \leq k
    \end{array}
\right\} = yz
\end{equation}

\end{document}

Summary

The simplest way to write a piecewise function in LaTex is to use the cases environment found inside the asmath package. It’s also semantically more appropriate.

You can also use the array environment under the same package. The only difference is that array comes with padding on the left and right. It is much easier to change the alignment of columns in array than with cases.