MATLAB Subplots: Plotting Cosine Functions with Varying Frequencies
Visualizing Cosine Functions with Varying Frequencies in MATLAB
This tutorial demonstrates how to create six subplots in MATLAB to visualize cosine functions with frequencies ranging from 1 to 6.matlab% Create theta values from -2pi to 2pitheta = linspace(-2pi, 2pi, 100);
% Create the figure with six subplotsfigure;
% Subplot 1: y = cos(theta)subplot(2, 3, 1);plot(theta, cos(theta));title('y = cos(\theta)');xlabel('\theta');ylabel('y');
% Subplots 2 to 6: y = cos(ntheta), n = 2 to 6for n = 2:6 subplot(2, 3, n); plot(theta, cos(ntheta)); title(['y = cos(', num2str(n), '\theta)']); xlabel('\theta'); ylabel('y');end
Explanation:
-
Define the Range: - We start by creating a variable
thetausinglinspace(-2*pi, 2*pi, 100). This generates 100 evenly spaced values between -2π and 2π, representing the input values for our cosine functions. -
Create the Figure and Subplots: - The
figurecommand creates a new figure window to hold our subplots. - We utilize thesubplot(2, 3, n)function to create six subplots arranged in two rows and three columns. Thenvariable specifies the current subplot's index, starting from 1 in the top left corner and increasing across rows. -
Plot the Cosine Functions: - For each subplot, we use the
plot(theta, cos(n*theta))command to plot the corresponding cosine function. - The frequency of the cosine function is controlled by the variablen, which ranges from 1 to 6. -
Add Titles and Labels: - We use
title,xlabel, andylabelfunctions to add descriptive titles and labels to each subplot, making it easier to understand the visualized data.
This script generates a figure containing six subplots, each displaying a cosine function with a different frequency. This visualization technique is helpful for understanding how changing the frequency of a cosine function affects its shape and characteristics.
原文地址: https://www.cveoy.top/t/topic/kP2 著作权归作者所有。请勿转载和采集!