Page 19 - Applied Numerical Methods Using MATLAB
P. 19
8 MATLAB USAGE AND COMPUTATIONAL ERRORS
We can also use the plot() command to draw a circle.
>>r = 1; th = [0:0.01:2]*pi; % [0:0.01:2] makes [0 0.01 0.02 .. 2]
>>plot(r*cos(th),r*sin(th))
>>plot(r*exp(j*th)) %alternatively,
Note that the plot() command with a sequence of complex numbers as its first
input argument plots the real/imaginary parts along the horizontal/vertical axis.
The polar() command plots the phase (in radians)/magnitude given as its
first/second input argument, respectively (see Fig.1.3a).
>>polar(th,exp(-th)) %polar plot of a spiral
Several other plotting commands, such as semilogx(), semilogy(), loglog(),
stairs(), stem(), bar()/barh(),and hist(), may be used to draw various
graphs (shown in Figs.1.3 and 1.4). Readers may use the ‘help’ command to get
the detailed usage of each one and try running the following MATLAB program
‘nm114 2.m’.
%nm114_2: plot several types of graph
th = [0: .02:1]*pi;
subplot(221), polar(th,exp(-th))
subplot(222), semilogx(exp(th))
subplot(223), semilogy(exp(th))
subplot(224), loglog(exp(th))
pause, clf
subplot(221), stairs([1 3 2 0])
subplot(222), stem([1 3 2 0])
subplot(223), bar([2 3; 4 5])
subplot(224), barh([2 3; 4 5])
pause, clf
y = [0.3 0.9 1.6 2.7 3 2.4];
subplot(221), hist(y,3)
subplot(222), hist(y,0.5 + [0 1 2])
Moreover, the commands sprintf(), text(),and gtext() are used for com-
bining supplementary statements with the value(s) of one or more variables to
construct a string and printing it at a certain location on the existing graph.
For instance, let us try the following statements in the MATLAB Command
window:
>>f = 1./[1:10]; plot(f)
>>n = 3; [s,errmsg] = sprintf(’f(%1d) = %5.2f’,n,f(n))
>>text(3,f(3),s) %writes the text string at the point (3,f(3))
>>gtext(’f(x) = 1/x’) %writes the input string at point clicked by mouse
The command ginput() allows you to obtain the coordinates of a point
by clicking the mouse button on the existent graph. Let us try the following