How to Plot an Equation in MATLAB

Ammar Ali Feb 02, 2024
  1. Plot an Equation Using plot() Function in MATLAB
  2. Plot an Equation Using ezplot() Function in MATLAB
How to Plot an Equation in MATLAB

In this tutorial, we will discuss how to plot an equation by declaring the value of the independent variables present in the equation and then using the plot() function to plot it and how to plot the equation using ezplot() in MATLAB.

Plot an Equation Using plot() Function in MATLAB

Consider you want to plot an equation in MATLAB which have one dependent variable and one or more independent variables. To plot the equation, you need to declare the independent variables present in the equation and then you can find the value of the dependent variable, and using these values you can plot the equation using the plot() function. For example, let’s plot an equation that has one dependent variable and one independent variable. See the code below.

a = -5:0.01:5;
b = cos(a).^2+cos(a).^3;
plot(a,b)

Output:

Plotting An Equation Using plot in Matlab

In the above code, we declared a random value of the independent variable to calculate the values of the dependent variable, you can change the values of the independent variable according to your requirements. You can also increase the number of independent variable according to you equation.

Plot an Equation Using ezplot() Function in MATLAB

Consider you want to plot an equation in MATLAB which have one dependent variable and one or more independent variables. To plot the equation using ezplot(), first, you need to define your equation as a function using the @() function and after that, you need to pass the independent variables inside the @() function. Finally, you can plot the equation using the ezplot() function. For example, let’s plot an equation that has one dependent variable and one independent variable. See the code below.

f = @(a) cos(a).^2+cos(a).^3;
ezplot(f)

Output:

Plotting An Equation Using ezplot in Matlab

In the above code, we declared the equation as a function f, and as you can see the output is the same as the above output with only deference in independent variable values. The ezplot() function automatically assigns values to the independent variables. You can also increase the number of independent variable according to you equation.

Author: Ammar Ali
Ammar Ali avatar Ammar Ali avatar

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook

Related Article - MATLAB Plot