Solutions to the Practice SetsSolutions to Practice Set A: Algebra and Arithmetic... Solutions to Practice Set A: Algebra and Arithmetic 221We get a one-parameter family of answers depen
Trang 1Here the vertical bar highlights the place where MATLAB believes the error is cated In this case, the actual error is earlier in the input line.
lo-Spelling Error
CAUSE: Using uppercase instead of lowercase letters in MATLAB commands, or spelling the command.
mis-SOLUTION: Fix the spelling
Consider the following accidental misspellings
Error or Warning Messages When Plotting
CAUSE: There are several possible explanations, but usually the problem is the wrong type of input for the plotting command chosen.
SOLUTION: Carefully follow the examples in the help lines of the plotting command, and
pay attention to the error and warning messages
Trang 2210 Chapter 11 Troubleshooting
0.5 1 1.5
Figure 11.1 A Spurious Graph of y = x 1/3
Figure 11.1 is not the graph of y = x 1/3on the interval−3 ≤ x ≤ 3 Actually, the
graph to the right of the origin looks correct, but to the left of the origin the graph
is certainly not right The warning message provides a clue What has happened is
that MATLAB is plotting the real part of x 1/3, but for a different branch of the
multi-valued function than the one we want MATLAB is interpreting x 1/3 for x negative
Figure 11.2 Correct Graph of y = x 1/3
A Previously Saved M-File Evaluates Differently
One of the most frustrating problems you may encounter occurs when a previouslysaved M-file, which you are sure is in good shape, won’t evaluate or evaluates incor-
Trang 3The Most Common Mistakes 211
rectly when opened in a new session
CAUSE: Change in the sequence of evaluation, or failure to initialize variables.
SOLUTION: Make sure to clear or initialize variables that are not inputs to the M-file
EXAMPLE: The problem is illustrated by the following simple, but poorly designed, program
To compute n! (n-factorial), a user writes the following script M-file:
Computer Won’t Respond
CAUSE: MATLAB is caught in a very large calculation, or some other calamity has occurred, which has caused it to fail to respond Perhaps you are using an array that is too large for your computer memory to handle.
SOLUTION: Abort the calculation with CTRL+C
If overuse of computer memory is the problem, try to redo your calculation usingsmaller arrays, e.g., by using fewer grid points in a 3D plot, or by breaking a largevectorized calculation into smaller pieces using a loop Clearing large arrays fromyour Workspace may help too
EXAMPLE: You’ll know it when you see it!
The Most Common Mistakes
The most common mistakes are all accounted for in the causes of the problems scribed earlier But to help you prevent these mistakes, we compile them here in asingle list to which you can refer periodically Doing so will help you to establish
de-“good MATLAB habits.”
• Forgetting to clear or initialize variables
• Improper use of built-in functions
• Inattention to the order of precedence of arithmetic operations
• Improper use of arithmetic symbols
• Mismatched delimiters
• Using the wrong delimiters
Trang 4212 Chapter 11 Troubleshooting
• Plotting the wrong kind of object
• Using uppercase instead of lowercase letters in MATLAB commands, or
mis-spelling commands
Debugging Techniques
Now that we have discussed the most common mistakes, it’s time to discuss how todebug your M-files, and how to locate and fix those pesky problems that don’t fit intothe neat categories above
If one of your M-files is not working the way you expected, perhaps the easiest
thing you can do to debug it is to insert the command keyboard somewhere in the
middle This temporarily suspends (but does not stop) execution and returns
com-mand to the keyboard, where you are given a special prompt with a K in it You can
execute whatever commands you want at this point (for instance, to examine some of
the variables) To return to execution of the M-file, type return or dbcont, short
for “debug continue.”
A more systematic way to debug M-files is to use the debugging features of the
MATLAB M-file Editor/Debugger Start by going to the menu item Tools:Check
Code with M-Lint This checks the code of the M-file for common mistakes and
syntax errors and prints out a report specifying where potential problems are located
(You can do the same thing from the Command Window with the command mlint
followed by a space and the name of the file.) Next, use the debugger to insert
“break-points” in the file Usually you would do this with the Breakpoints menu or with the
“Set/clear breakpoint” icon at the top of the Editor/Debugger window, but you can
also do it from the Command Window with the command dbstop (See its online
help.) Once a breakpoint has been inserted in the M-file, you will see a little red dotnext to the appropriate line in the Editor/Debugger (An example is illustrated in Fig-ure 11.8 below.) Then, when you call the M-file, execution will stop at the breakpoint,
and, just as in the case of keyboard, control will return to the Command Window, where you will be given a special prompt with a K in it Again, when you are ready to resume execution of the M-file, type dbcont When you have finished the debugging process, dbclear “clears” the breakpoint from the M-file.
Let’s illustrate these techniques with a real example Suppose that you want to
construct a function M-file that takes as input two expressions f and g (given either
as symbolic expressions or as strings) and two numbers a and b, plots the functions
f and g between x = a and x = b, and shades the region in between them As a
first try, you might start with the nine-line function M-file shadecurves.m given
as follows:
function shadecurves(f, g, a, b)
%SHADECURVES Draws the region between two curves
% SHADECURVES(f, g, a, b) takes strings or expressions f
% and g, interprets them as functions, plots them between
% x = a and x = b, and shades the region in between.
% Example: shadecurves(’sin(x)’, ’-sin(x)’, 0, pi)
Trang 5Debugging Techniques 213
ffun = inline(vectorize(f)); gfun = inline(vectorize(g)); xvals = a:(b - a)/50:b;
plot([xvals, xvals], [ffun(xvals), gfun(xvals)])
Let’s run the M-file with the data specified in the help lines:
Figure 11.3 A First Attempt at Shading the Region between sin x and − sin x.
The graph in Figure 11.3 was obtained by executing
>> shadecurves(’sin(x)’, ’-sin(x)’, 0, pi)
or
>> syms x; shadecurves(sin(x), -sin(x), 0, pi)
This is not really what we wanted; the figure we seek is shown in Figure 11.4
Figure 11.4 The Shaded Region between sin x and − sin x.
To begin to determine what went wrong, let’s try a different example, say
>> syms x; shadecurves(xˆ2, sqrt(x), 0, 1); axis square
Now we get the output shown in Figure 11.5
Trang 6214 Chapter 11 Troubleshooting
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Figure 11.5 A First Attempt at Shading the Region between x2and√
x.
It’s not too hard to figure out why our regions aren’t shaded; that’s because we used
plot (which plots curves) instead of patch (which plots filled patches) So that
suggests we should try changing the last line of the M-file to:
patch([xvals, xvals], [ffun(xvals), gfun(xvals)])
That gives the error message:
??? Error using ==> patch
Not enough input arguments.
Error in ==> shadecurves at 9
patch([xvals, xvals], [ffun(xvals), gfun(xvals)])
so we go back and try
>> help patch
to see whether we can get the syntax right The help lines indicate that patch
re-quires a third argument, the color (in RGB coordinates) with which our patch is to befilled So we change our final line to, for instance,
patch([xvals, xvals], [ffun(xvals), gfun(xvals)], [.5,0,.7])
That gives us now as output to
>> syms x; shadecurves(xˆ2, sqrt(x), 0, 1); axis square
the picture shown in Figure 11.6
That’s better, but still not quite right, because we can see a mysterious diagonalline down the middle Not only that, but if we try
>> syms x; shadecurves(xˆ2, xˆ4, -1.5, 1.5)
we now get the bizarre picture shown in Figure 11.7
There aren’t a lot of lines in the M-file, and lines 7 and 8 seem OK, so the problem
must be with the last line We need to reread the online help for patch It indicates that patch draws a filled two-dimensional polygon defined by the vectors X and
Trang 7Debugging Techniques 215
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Figure 11.6 A Second Attempt at Shading the Region between x2and√
x.
−1.50 −1 −0.5 0 0.5 1 1.5 1
2 3 4 5 6
Figure 11.7 A First Attempt at Shading the Region between x2and x4
Y, which are its first two inputs A way to see how this is working is to changethe “50” in line 9 of the M-file to something much smaller, say 5, and then insert abreakpoint in the M-file before line 9 At this point, our M-file in the Editor/Debuggerwindow now looks like Figure 11.8 Note the large dot to the left of the last line,indicating the breakpoint When we run the M-file with the same input, we now
obtain in the Command Window a K>> prompt At this point, it is logical to try to list
the coordinates of the points that are the vertices of our filled polygon, so we try
K>> [[xvals, xvals]’, [ffun(xvals), gfun(xvals)]’]
Trang 82 3 4 5 6
Figure 11.9 A Second Attempt at Shading the Region between x2and x4
Finally we can understand what is going on; MATLAB has “connected the dots”using the points whose coordinates were just printed out In particular, MATLAB hasdrawn a line from the point (1.5, 2.25) to the point (−1.5, 5.0625) This is not what
we wanted; we wanted MATLAB to join the point (1.5, 2.25) on the curve y = x2to
the point (1.5, 5.0625) on the curve y = x4 We can fix this by reversing the order
of the x-coordinates at which we evaluate the second function g So, letting slavx
Trang 9Debugging Techniques 217
denote xvals reversed, we correct our M-file to read:
function shadecurves(f, g, a, b)
%SHADECURVES Draws the region between two curves
% SHADECURVES(f, g, a, b) takes strings or expressions f
% and g, interprets them as functions, plots them between
% x = a and x = b, and shades the region in between.
% Example: shadecurves(’sin(x)’, ’-sin(x)’, 0, pi)
ffun = inline(vectorize(f)); gfun = inline(vectorize(g)); xvals = a:(b - a)/50:b; slavx = b:(a - b)/50:a;
patch([xvals, slavx], [ffun(xvals), gfun(slavx)], [.5,0,.7])
Now it works properly Sample output from this M-file is shown in Figure 11.4 Try
it out on the other examples we have discussed, or on others of your choice
Trang 11Solutions to the Practice Sets
Solutions to Practice Set A: Algebra and Arithmetic
Trang 12220 Solutions to the Practice Sets
Trang 13Solutions to Practice Set A: Algebra and Arithmetic 221
We get a one-parameter family of answers depending on the variable y In fact the
three planes determined by the three linear equations are not independent, because thefirst equation is the sum of the second and third The locus of points that satisfy thethree equations is not a point, the intersection of three independent planes, but rather
a line, the intersection of two distinct planes Once again we check
Trang 14222 Solutions to the Practice Sets
Let’s try simple instead.
[better, how] = simple(cos(x)ˆ2 - sin(x)ˆ2)
Trang 15Solutions to Practice Set A: Algebra and Arithmetic 223
But note the following:
Trang 16224 Solutions to the Practice Sets
[ 1/3 p 1/2 / 1/3 p \] [- 1/12 %1 + - - 1/2 I 3 |1/6 %1 + 2 -|]
Trang 17Solutions to Practice Set A: Algebra and Arithmetic 225
Trang 18226 Solutions to the Practice Sets
Trang 19Solutions to Practice Set A: Algebra and Arithmetic 227
This is better, but because of the wild oscillation near x = 0, neither plot nor
ezplotgives a totally accurate graph of the function
(d)
X = -1.5:0.01:1.5;
plot(X, exp(-X.ˆ2), X, X.ˆ4 - X.ˆ2)
Trang 20228 Solutions to the Practice Sets
Let’s plot 2x and x4 and look for points of intersection We plot them first with
ezplotjust to get a feel for the graph
ezplot(’xˆ4’); hold on; ezplot(’2ˆx’); hold off
points of intersection between−2 and 2 Let’s change to plot now and focus on the
interval between−2 and 2 We’ll plot x4dashed
X = -2:0.1:2; plot(X, 2.ˆX);
hold on; plot(X, X.ˆ4, ’ ’); hold off
Trang 21Solutions to Practice Set A: Algebra and Arithmetic 229
We see that there are points of intersection near−0.9 and 1.2 Are there any other
points of intersection? To the left of 0, 2x is always less than 1, whereas x4goes to
infinity as x goes to negative infinity On the other hand, both x4and 2xgo to infinity
as x goes to infinity, so the graphs may cross again to the right of 6 Let’s check.
We see that they do cross again, near x = 16 If you know a little calculus, you can
show that the graphs never cross again (by taking logarithms, for example), so we
have found all the points of intersection Now let’s use fzero to find these points
of intersection numerically This command looks for a solution near a given startingpoint To find the three different points of intersection we will have to use threedifferent starting points The above graphical analysis suggests appropriate startingpoints
r1 = fzero(’2ˆx - xˆ4’, -0.9)
r2 = fzero(’2ˆx - xˆ4’, 1.2)
r3 = fzero(’2ˆx - xˆ4’, 16)
Trang 22230 Solutions to the Practice Sets
Trang 23Solutions to Practice Set B: Calculus, Graphics, and Linear Algebra 231
The function lambertw is a “special function” that is built into MATLAB You can learn more about it by typing help lambertw Let’s see the decimal values of the
Trang 24232 Solutions to the Practice Sets
Trang 25Solutions to Practice Set B: Calculus, Graphics, and Linear Algebra 233
contour(X, Y, Y.*log(X) + X.*log(Y), [0 0], ’k’)
Warning: Log of zero.
Warning: Log of zero.
Trang 26234 Solutions to the Practice Sets
Trang 27Solutions to Practice Set B: Calculus, Graphics, and Linear Algebra 235
Trang 28236 Solutions to the Practice Sets
Trang 29Solutions to Practice Set B: Calculus, Graphics, and Linear Algebra 237
syms x; int(exp(sin(x)), x, 0, pi)
Warning: Explicit integral could not be found.
Trang 30238 Solutions to the Practice Sets
MATLAB integrated this one exactly in 3(e) above; let’s integrate it numerically and
compare answers Unfortunately, the range is infinite, so to use quadl we have to
approximate the interval Note that
exp(-35)
ans =
6.305116760146989e-16
which is close to the standard floating-point accuracy, so
format long; quadl(@(x) exp(-x.ˆ2), -35, 35)
Trang 31Solutions to Practice Set B: Calculus, Graphics, and Linear Algebra 239
ezplot(sin(1/x), [0 1])
Trang 32240 Solutions to the Practice Sets