How to Plot Sine Wave in Matlab

Ammar Ali Feb 02, 2024
How to Plot Sine Wave in Matlab

This tutorial will discuss how to plot a sine wave using the plot() function in MATLAB.

Plot a Sine Wave Using the plot() Function in MATLAB

To plot two variables on a graph, we require multiple values of these variables so that the plot is smooth. In MATLAB, the plot() also does the same, it plots the data points on a graph, and then it connects each data point to get a smooth plot. So, if you want to plot a sine wave, you need to define the time variable, which will contain some time value, for example, a time of 1s to 2s. As we know, there are infinite values between 1 and 2, but in the case of a computer, we have to define some finite values so that we can get our output in a short period of time. In MATLAB, we can define how many values we want between 1 and 2 using a step value. For example, see the code below.

t = 1:0.01:2;

In the above code, the time is from 1s to 2s, but it contains 100 values. The next step is to find the value of the sine function on the given time values and then plot a graph on these two values. See the code below.

t = 1:0.01:2;
s = sin(2*pi*t);
plot(t,s)

Output:

Plotting sine wave in matlab

In the above code, the pi variable contains the value 3.14. As you can see in the output, the plot of the sine wave is a smooth plot, but if we lower the data points or values of the variable t the plot will be smooth. This plot is continuous, but you can also change the plot to discrete to better understand the plotting method. See the example code below.

t = 1:0.01:2;
s = sin(2*pi*t);
plot(t,s,'*')

Output:

Plotting discreate sine wave

In the above code, we used the asterisk character to plot the data points. As you can see in the output, there are exactly 100 asterisks plotted. Check this link for more details about the plot() function.

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