How to Plot a Function in MATLAB

MATLAB is a program used primarily by engineers and scientists for analysis. We will demonstrate how to plot any function in MATLAB and edit it afterward to add labels, grids, extra plots, and cosmetic changes. We are using MATLAB R2022a for the guide.

Plotting a function

MATLAB has multiple tools to plot a function. However, the best way is to use fplot.

fplot(f, [xmin max]) lets you plot a function f(x) in the domain of xmin to xmax.

We will use an example function y=cos(x) over the period -10 to 10.

Example plot

fplot(@(x) cos(x), [-10 10])
Graph of y=cos(x) from -10 to 10

Adding to the plot

We can add different lines to our plot using hold, for example:

fplot(@(x) cos(x), [-10 10])
hold on
fplot(@(x) cos(x+pi/2), [-10 10], 'g')

Here ‘g’ (green) is setting the color and style of the second line to differentiate it from the first line. The other colors and line styles that can be chosen are described in the formatting section below.

2 lines plot
Graph of y=cos(x) and y=cos(x+pi/2) from -10 to 10

How to Plot Piecewise functions

For functions that are defined in different ranges, such as

  • cos(x) -10 <x<0
  • sin(x) 0<x<10

we can again use hold to plot them

fplot(@(x) cos(x),[-10 0])
hold on
fplot(@(x) sin(x),[0 10])
hold off
Piecewise function
Graph of piecewise function

How to plot a Parametric functions

An example is best used to illustrate how to plot a parametric curve.

Take the following parametric function:

  • x=sin(t)
  • y=e0.5t

We will write the following

xt = @(t) sin(t);

yt = @(t) exp(t/2);



Parametric curve
Graph of a parametric function

At this point, we have learned how to plot a function. All that is left is to make cosmetic changes for visibility.

How to format the Plot

We can add titles, grid, and labels to the plot using the following commands for our initial example plot of cos(x)

grid on

As in the example below, the line color, thickness, and markers can easily be changed.

fplot(@(x) cos(x), [-10 10], 'color', 'r', 'LineWidth', 5, 'LineStyle', '--')

Here the ‘color’ can be set to ‘r’ed, ‘g’reen, ‘b’lue, ‘c’yan, ‘m’agenta, ‘y’ellow, ‘b’lack and ‘w’hite.
The ‘LineStyle’ can be set to ‘-‘ , ‘–‘ , ‘:’ , ‘-.’ or ‘none’.
The ‘LineWidth’ is default set to 0.5.

Edited plot
Example graph showing labels, grid, and different line colors and styles

Was this article helpful?

Leave a Comment