Matlab Commands 02-12-21
Matlab Commands 02-12-21
Define x, by specifying the range of values for the variable x, for which the function is
to be plotted
Define the function, y = f(x)
Call the plot command, as plot(x, y)
Following example would demonstrate the concept. Let us plot the simple function y = x for the
range of values for x from 0 to 100, with an increment of 5.
x = [0:5:100];
y = x;
plot(x, y)
When you run the file, MATLAB displays the following plot −
Let us take one more example to plot the function y = x2. In this example, we will draw two
graphs with the same function, but in second time, we will reduce the value of increment. Please
note that as we decrease the increment, the graph becomes smoother.
x = [1 2 3 4 5 6 7 8 9 10];
x = [-100:20:100];
y = x.^2;
plot(x, y)
When you run the file, MATLAB displays the following plot −
Change the code file a little, reduce the increment to 5 −
x = [-100:5:100];
y = x.^2;
plot(x, y)
The xlabel and ylabel commands generate labels along x-axis and y-axis.
The title command allows you to put a title on the graph.
The grid on command allows you to put the grid lines on the graph.
The axis equal command allows generating the plot with the same scale factors and the
spaces on both axes.
The axis square command generates a square plot.
Example
x = [0:0.01:10];
y = sin(x);
plot(x, y), xlabel('x'), ylabel('Sin(x)'), title('Sin(x) Graph'),
grid on, axis equal
Example
Code Color
w White
k Black
b Blue
r Red
c Cyan
g Green
m Magenta
y Yellow
Example
When you run the file, MATLAB generates the following graph −
Example
x = [0 : 0.01: 10];
y = exp(-x).* sin(2*x + 3);
plot(x, y), axis([0 10 -1 1])
When you run the file, MATLAB generates the following graph −
Generating Sub-Plots
When you create an array of plots in the same figure, each of these plots is called a subplot. The
subplot command is used for creating subplots.
subplot(m, n, p)
where, m and n are the number of rows and columns of the plot array and p specifies where to
put a particular plot.
Each plot created with the subplot command can have its own characteristics. Following example
demonstrates the concept −
Example
y = e−1.5xsin(10x)
y = e−2xsin(10x)
x = [0:0.01:5];
y = exp(-1.5*x).*sin(10*x);
subplot(1,2,1)
plot(x,y), xlabel('x'),ylabel('exp(–1.5x)*sin(10x)'),axis([0 5 -1 1])
y = exp(-2*x).*sin(10*x);
subplot(1,2,2)
plot(x,y),xlabel('x'),ylabel('exp(–2x)*sin(10x)'),axis([0 5 -1 1])
When you run the file, MATLAB generates the following graph −