Open In App

Plot Expression or Function in MATLAB

In this article, we will discuss how to plot expressions or functions in MATLAB. We can make use fplot() function in MATLAB to generate the plot corresponding to an expression or function.

There are different variants of fplot() function



  1. fplot(f)
  2. fplot(f,xinterval)
  3. fplot(___,LineSpec)
  4. fplot(___,Name,Value)

Now discussing each variant in detail. Below are the various ways to plot an expression or a function in MATLAB: 

fplot(f): Plots the expression passed to it as a parameter.



Example : Plotting cos(x) function in default interval [-5 5]




% Plots cos(x) function from x=-5 to 5
fplot(@(x) cos(x))

Output :

fplot(f,xinterval): Plots the curve defined by function y = f(x) in the specified interval. Specify the interval as a two-element vector of the form [xmin xmax].

Example : Plotting cos(x) function in the interval [-3 3].




% Plots the sin(x) cureve from x =[-3:3]
fplot(@(x) sin(x),[-3 3])

Output :

fplot(___,LineSpec)

Some values of each property are

Linestyle Meaning Marker Meaning Color Meaning
‘-‘ Solid ‘o’ Circle ‘r’ Red
‘:’ Dotted ‘+’ Plus sign ‘q’ Green
‘–‘ Dashed ‘*’ Asterik ‘b’ Blue

Example : Plotting exp(x) function in the interval [-5 8] with a red solid line with star marker.




% plotting exp(x) function in the interval [-5 8] 
% with a red solid line with star marker.
fplot(@(x) exp(x),[-5 8],'-*r')

Output :

fplot(___,Name,Value)

Example : Plot the sin(2x) function with a linewidth of 2, and blue dotted line with a circle marker by specifying their name and value pairs.




% Plot the sin(2x) function with a 
% linewidth of 2, and blue dotted 
% line with circle marker
fplot(@(x) sin(2*x),[-5 8],'Color','b','Marker','o',
'LineWidth',2,'LineStyle','--')

Output :

We can depict multiple expressions in a single plot. Below is an example where we plot sin(x) and cos(2*x) in the same illustration:




% Plotting sin(x)
fplot(@(x) sin(x))
hold on 
  
% Resuming the plot and 
% including cos(2*x)
fplot(@(x) cos(2*x))
hold off

Output :

In the above program, we depict two expressions in the same plot. The hold keyword is used in MATLAB to hold on and hold off expressions in a plot.


Article Tags :