Ma · Mathematics

How to Create Triangular and Step Functions in MATLAB

Published By the 9to5Science editorial team

At a glance

  1. 1. Choose the function

    Decide whether you need a unit step, a finite triangular pulse, a periodic triangle wave, or a piecewise-constant function.

  2. 2. Build it from conditions

    Use logical comparisons such as t >= 0 to create numeric step values without requiring a toolbox.

  3. 3. Combine and plot

    Add shifted steps for piecewise functions, or use a formula for a triangle; plot the result to check its shape.

  4. 4. Check endpoints

    Choose whether a step includes its threshold, and remember that symbolic and numeric step conventions can differ.

MATLAB can represent step-shaped functions directly with vectorized logical comparisons. This is often the simplest choice for numerical work: it needs no special toolbox and works on arrays as well as scalars.

“Triangular function” can mean either a single triangular pulse or a repeating triangle wave. These have different formulas, so the examples below show both, along with unit steps and piecewise-constant functions.

Make a numeric unit step

A common convention for the unit step is

u(t)=\begin{cases}0,&t<0,\\1,&t\geq 0.\end{cases}$$ For a numeric vector `t`, implement that convention as: ```matlab u = double(t >= 0); ``` The comparison returns a logical array: `false` where `t < 0` and `true` where `t >= 0`. Converting it with `double` gives zeros and ones. For example: ```matlab t = -2:0.5:2; u = double(t >= 0); ``` At `t = 0`, this version returns 1. That endpoint choice is conventional, not universal. In symbolic mathematics, the Heaviside step is often assigned the value 1/2 at zero; MATLAB's Symbolic Math Toolbox provides `heaviside`, but its symbolic behavior and toolbox requirements differ from this basic numeric implementation. ## Build rectangular and piecewise-constant functions Subtracting two shifted steps creates a rectangular pulse. For `a < b`, $$p(t)=u(t-a)-u(t-b)$$ is 1 on $[a,b)$ and 0 elsewhere under the convention above. In MATLAB: ```matlab a = -1; b = 2; p = double(t >= a) - double(t >= b); ``` You can also construct a piecewise-constant function by adding step changes. Start with a baseline value, then add each jump at its threshold. For example, the function that is 0 before -1, 2 from -1 up to 1, and -1 from 1 onward has jumps of +2 and -3: ```matlab f = 2*double(t >= -1) - 3*double(t >= 1); ``` More generally, if the baseline is `c0`, and the changes in value are `jumps(k)` at thresholds `thresholds(k)`, use a loop: ```matlab f = c0 * ones(size(t)); for k = 1:numel(thresholds) f = f + jumps(k) * double(t >= thresholds(k)); end ``` `thresholds` and `jumps` should have the same number of elements. The jump at each threshold is included at that point because the comparison is `>=`. ## Make a triangular pulse A symmetric triangular pulse centered at zero, with peak 1 and zeros at $-a$ and $a$ for `a > 0`, is $$q(t)=\max\left(1-\frac{|t|}{a},0\right).$$ The MATLAB expression is: ```matlab a = 2; q = max(1 - abs(t)/a, 0); ``` For the sample vector `t = -2:0.5:2` and `a = 2`, the pulse is zero at both ends, reaches 1 at zero, and is linear between those points. Outside the interval $[-a,a]$, it stays zero. To change the peak height to `A`, multiply the expression by `A`. ## Make a periodic triangle wave A triangle wave repeats indefinitely, unlike the single pulse above. One version with period `T` and values between -1 and 1 is: ```matlab T = 2; triangle = 1 - 4*abs(mod(t/T, 1) - 0.5); ``` Here, `mod(t/T,1)` gives the position within each period. The wave is -1 at integer multiples of `T`, rises linearly to 1 halfway through each period, then falls back to -1. If you want a wave that starts at zero and first rises, you can instead use: ```matlab triangle = (2/pi) * asin(sin(2*pi*t/T)); ``` Both formulas produce a triangle wave, but their phase—the point in the cycle used as the starting position—is different. ## Plot the examples This script plots the unit step, rectangular pulse, triangular pulse, and periodic triangle wave together: ```matlab t = -4:0.01:4; a = 2; b = 1; T = 2; u = double(t >= 0); p = double(t >= -1) - double(t >= 1); q = max(1 - abs(t)/a, 0); triangle = 1 - 4*abs(mod(t/T, 1) - 0.5); figure subplot(2,2,1), plot(t,u), title('Unit step'), ylim([-0.2 1.2]) subplot(2,2,2), plot(t,p), title('Rectangular pulse'), ylim([-0.2 1.2]) subplot(2,2,3), plot(t,q), title('Triangular pulse'), ylim([-0.2 1.2]) subplot(2,2,4), plot(t,triangle), title('Triangle wave'), ylim([-1.2 1.2]) ``` The variable `b` is not needed in this plotting script and may be omitted; the pulse endpoints are set directly to -1 and 1. Each subplot uses the same sampled time vector, so the discontinuities and corners are connected by straight line segments between samples. ## Common mistakes - **Mixing up a pulse and a wave:** a triangular pulse is nonzero only on a finite interval; a triangle wave repeats. - **Ignoring the step convention at the threshold:** `t >= a` includes the threshold, while `t > a` excludes it. This matters for discrete samples and exact endpoint values. - **Calling a symbolic function on numeric data unnecessarily:** logical comparisons are simpler for numeric arrays. `heaviside` is useful when you need symbolic expressions, but requires the Symbolic Math Toolbox. - **Using too few plot samples:** a coarse time grid can make corners look rounded or miss a narrow pulse. Use a finer spacing when plotting sharp features. For integration of ordinary functions, the value assigned at a single step discontinuity does not change the integral. For sampled data, however, that value is part of the array and should match the convention you intend to use.

References

  1. MathWorks documentation: heaviside
  2. MathWorks documentation: Logical Operations

Spotted an error? Send a correction. Read how we write and check articles in our editorial policy.