Introduction to Computing
Plotting
plot (x,y)
is used to plot a function y=f(x),
plots the x values on the horizontal axis and the y values on
the vertical axis.
xlabel (‘text’) and ylabel (‘text’): put labels on horizontal and
vertical axis.
title (‘text’): puts a title at the top of the plot.
>> x=[0:0.1:52];
>> y=0.4.*sqrt(1.8.*x);
>> plot(x,y)
>> xlabel('Distance (miles)')
>> ylabel('Height (miles)')
>> title('Rocket height as a
function of Downrange Distance')
Practice: Draw y=sin(x) , z=2cos(x) and t=y+z with 0x1800
grid: displays gridlines at the tick marks corresponding to the
tick labels.
grid on: add gridlines
grid off: stop plotting gridlines
axis: override the Matlab selections for the axis limits.
axis ([xmin xmax ymin ymax]): sets the scaling for the x- and
y- axes to the minimum and maximum values indicated, not use
commas to separate the values.
Practice:
Given y=sin (x) , z=2cos(x) and t=y+z . Draw t using grid, axis.
(the limit on x and y are optional.)
The axis command has the following variants:
axis square: selects the axes’ limits so that the plot will be
square.
axis equal: selects the scale factors and tick spacing to be
the same on each axis. This makes plot(sin(x),cos(x)) look like
a circle, instead of an oval.
axis auto: returns the axis scaling to its default autoscaling
mode in which the best axes limits are computed automatically.
>> x=[0:0.1:52];
>> y=0.4*sqrt(1.8*x); y1 = x;
>> plot(x,y), xlabel('Distance (miles)'), ylabel('Height (miles)'), title('Rocket height as
a function of Downrange Distance'), grid on, axis ([0 52 0 5])
fplot(‘string’, [xmin xmax])
‘string’: a text string, describes the function to be plotted
[xmin xmax]: specifies the minimum and maximum values of
the independent variable.
The range of the dependent variable can also be specified:
fplot(‘string’, [xmin xmax ymin ymax])
[x,y]=fplot(‘string’, limits)
limits may be [xmin xmax] or [xmin xmax ymin ymax]
>> f='cos(tan(x))-tan(sin(x))';
>> fplot(f,[1 2])
>> x=[1:0.01:2];
>> y=cos(tan(x))-tan(sin(x));
>> plot(x,y)
polyval: plot polynomials. (Chapter 2)
Ex: 3 x 5 2 x 4 100 x 3 2 x 2 7 x 90 ,6 x 6
>> x=[-6:0.01:6];
>> p=[3,2,-100,2,-7,90];
>> plot(x,polyval(p,x)),xlabel('x'),ylabel('p')
1. Plot the equation: y 0 .4 1 .8 x ,0 x 35 ,0 y 3 .5
2. Use fplot command to investigate the function tan(cos(x))-
sin(tan(x)) for 0≤x≤2.
How many values of x are needed to obtain the same plot
using the plot command?
subplot : obtain several smaller “subplots” in the same figure.
Syntax: subplot(m,n,p)
divides the Figure window into an array of rectangular panes
with m rows and n columns. The variable p tells Matlab to place
the output of the plot command following the subplot command
into the pth pane.
Ex: subplot(3,2,5) creates an array of six panes, three panes deep and
two panes across, and directs the next plot to appear
in the fifth pane (in the bottom-left corner).
Ex: Plot the function
y e 1.2 x sin 10 x 5 for 0 x5 and y x 3 100 for 6 x 6
>> x=[0:0.01:5];
>> y=exp(-1.2*x).*sin(10*x+5);
>> subplot(1,2,1)
>> plot(x,y),xlabel('x'),ylabel('y'),axis([0 5 -1 1])
>> x=[-6:0.01:6];
>> y=abs(x.^3-100);
>> subplot(1,2,2)
>> plot(x,y),xlabel('x'),ylabel('y'),axis([-6 6 0 350])
Pick a suitable spacing for t and v, and use subplot command
to plot the function z and u defined as below. Label each axis.
z e 0.5t cos20t 6 for 0t 8
u 6 log10 v 2 20 for 8 v 8
Use the variants of the MATLAB basic plotting functions
plot(x,y) and plot(y) to create overlay plots.
plot(A): plots the colums of A versus their indices and
generates n curves where A is a matrix with m rows and n
columns.
plot(x,A): plots the matrix A versus the vector x, where x is
either a row vector or column vector and A is a matrix with m
rows and n columns.
plot(A,x): plots the vector x versus the matrix A.
If the length of x is m x is plotted versus the columns of A.
If the length of x is n x is plotted versus the rows of A.
plot(A,B); plot the columns of the matrix B versus the columns
of the matrix A.
To plot the vector y versus the vector x and mark each point
with a data marker, enclose the symbol for the marker in single
quotes in the plot function.
Some specifiers for data markers, line types, and colors
Data markers Line types Colors
Dot (.) . Solid line - Black k
Asterisk (*) * Dashed line -- Blue b
Cross (x) x Dash-dotted line -. Cyan c
Circle (o) o Dotted line : Green g
Plus sign (+) + Magenta m
Square () s Red r
Diamond () d White w
Five-pointed star p Yellow y
Ex: >> x=[0:0.1:pi];
>> y=sin(x);
>> plot(x,y,'o')
>> x=[0:0.1:pi];
>> y=sin(x);
>> plot(x,y,x,y,'o')
Practice:
Using subplot command to plot the function
y= 2(x-1)Sinx + 3
in 6 small windows with 6 different formats in data
markers, line types and colors.
When more than one curve or data set is plotted on a graph
Distinguish between them by using different symbols or
different line types provide a legend or place a label next to
each curve.
legend command.
Ex: legend(‘string1’, ‘string2’)
string1 and string 2 are text strings of your choice.
legend command must be placed somewhere after the plot
command
Use the mouse t position the legend
>> x=[0:0.01:2];
>> y=sinh(x);
>> z=tanh(x);
>> plot(x,y,x,z,'--'),xlabel ('x'),ylabel ('Hyperbolic Sine and
Tangent'),legend('sinh(x)','tanh(x)')
Ex: Plot the real part and imaginary part of this function in one
figure:
y (t ) e 0.2t Cos(t ) i Sin(t) , 0 t 4
- Real part: red, solid line with * marker, linewidth = 1
- Imaginary part: green, dashed line with o marker, linewidth =
2
- Xlabel: t
- Ylabel: y(t)
- Title: Quiz 15/05/2021
- Legend: Real Part, Imaginary Part
t = 0:pi/20:4*pi;
y=exp(-0.2*t).*(cos(t)+i*sin(t));
plot (t,y, ‘LineWidth’,2);
title(‘\bfPlot of complex function vs time’);
xlabel(‘\bf\itt’);
ylabel(‘\bf\ity(t)’);
Imaginary parts of complex X and/or Y
arguments ignored
If both the real and imaginary parts of the function are of
interest the user has several choices. Both parts can be
plotted as a function of time on the same axes.
t = 0:pi/20:4*pi;
y = exp(-0.2*t).*(cos(t)+i*sin(t));
plot(t,real(y), ‘b-’, ‘LineWidth’,2);
hold on;
plot(t,imag(y), ‘r--’, ‘LineWidth’,2);
title(‘\bfPlot of complex function vs
time’);
xlabel(‘\bf\itt’);
ylabel(‘\bf\ity(t)’);
legend(‘real’, ‘imaginary’);
hold off;
The real part of the function can be plotted versus the
imaginary part. If a single complex argument is supplied
to the plot function, it automatically generates a plot of
the real part versus the imaginary part.
t = 0:pi/20:4*pi;
y = exp(-0.2*t).*(cos(t)+i*sin(t));
plot(y, ‘b-’, ‘LineWidth’,2);
title(‘\bfPlot of complex function’);
xlabel(‘\bfReal part’);
ylabel(‘\bfImaginary part’);
The function can be plotted as a polar plot showing
Magnitude versus angle.
t = 0:pi/20:4*pi;
y = exp(-
0.2*t).*(cos(t)+i*sin(t));
polar(angle(y),abs(y));
title(‘\bfPlot of complex
function’);
text command
text(x,y, ‘string’) : adds a text string to the plot at the location
specified by the coordinates x, y.
gtext(‘string’) : place the label next to the plot, where string is a
text string that specifies the label of your choice.
>> x=[0:0.01:1];
>> y=tan(x);
>> z=sec(x);
>>
plot(x,y,x,z),xlabel('x'),ylabel('Tangent
and Secant'),gtext('tan(x)'),text
(0.3,1.2,'sec(x)')
You can create text, titles, and labels that contain mathematical
symbols, Greek letters, and other effects such as italics.
The text, gtex, title, xlabel and ylabel commands all require a
string as their argument.
Ex:
>> title('A*exp(-t/tau)sin(omega t)')
>> title('Ae^{-t/\tau}sin(\omega t)')
Three-dimensional Line Plots
Lines in three-dimensional space can be plotted with the plot3
function.
Syntax: plot3(x,y,z)
Ex: x e 0.05t sin t
y e 0.05t cos t
z t
>> t=[0:pi/50:10*pi];
>> plot3(exp(-0.05*t).*sin(t),exp(-0.05*t).*cos(t),t)
>> xlabel('x'),ylabel('y'),zlabel('z'), grid
Surface mesh plots
z=f(x,y) represents a surface when plotted on xyz axes, and the
mesh function provides the means to generate a surface plot.
Generate a grid of these points in the xy plane first, and then
evaluate the function f(x,y) at these point.
Surface mesh plots
meshgrid: generate the grid.
[X,Y]=meshgrid(x,y)
If x=[xmin:xspacing:xmax], y=[ymin:yspacing:ymax]
the function will generate the coordinates of a rectangular with
one corner at (xmin, ymin) and the opposite corner at (xmax, ymax).
Each rectangular panel in the grid will have a width equal to xspacin
and a depth equal to yspacing.
[X,Y]=meshgrid(x) is equivalent to [X,Y]=meshgrid(x,x)
[X,Y]=meshgrid(min:spacing:max)
>> [X,Y]=meshgrid(-2:0.1:2);
>> Z=X.*exp(-((X-Y.^2).^2+Y.^2));
>> mesh(X,Y,Z),xlabel('x'),ylabel('y'),zlabel('z')
Contour plots
contour(X,Y,Z)
>> [X,Y]=meshgrid(-2:0.1:2);
>> Z=X.*exp(-((X-Y.^2).^2+Y.^2));
>> contour(X,Y,Z),xlabel('x'),ylabel('y')
PRACTICE 2
Create the surface mesh plot and a contour plot of the function
z x 2 2 xy y
2 2
Then use subplot to draw the following functions in the
same page, with 0t10.
v(t)=10e(-0.2+j)t