




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































(^1) These are course notes for Math 464/5/6, given Autumn 2006 through Spring 2007 at the University
of Washington by Anne Greenbaum. Professor Greenbaum and Professor Chartier retain the copyright to these notes. They do not give anyone permission to copy computer files related to them. Send email to [email protected].
are described in programs throughout the book. For further information about using MATLAB, we recommend [11].
1.1 Launching MATLAB
MATLAB is a high level programming language that is especially well-suited to linear algebra type computations, but it can be used for almost any numerical problem. Following are some of the basic features of MATLAB that you will need to carry out the programming exercises in this book. Depending on what system you are using, you will start MATLAB either by double clicking on a MATLAB icon or by typing ‘matlab’ or by some similar means. When MATLAB is ready for input from you it will give a prompt such as >>. You can use MATLAB like a calculator. For instance, if you type at the prompt:
>> 1+2*
then MATLAB returns with the answer:
ans =
7
Since you did not give a name to your result, MATLAB stores the result in a variable called ‘ans’. You can do further arithmetic using the result in ‘ans’:
>> ans/
and MATLAB will return with the result:
ans =
1.2 Vectors
MATLAB can store row or column vectors. The following commands:
>> v = [1; 2; 3; 4]
v =
1 2 3 4
>> w = [5, 6, 7, 8]
w =
5 6 7 8
create a column vector v of length 4 and a row vector w of length 4. In general, when defining a matrix or vector, semicolons are used to separate rows, while commas or spaces are used to separate the entries within a row. You can refer to an entry of a vector by giving its index:
>> v(2)
ans =
2
>> w(3)
ans =
7
MATLAB can add two vectors of the same dimension, but it cannot add v and w because v is 4 × 1 and w is 1 × 4. If you try to do this, MATLAB will give an error message:
>> v+w ??? Error using ==> + Matrix dimensions must agree.
The transpose of w is denoted w’:
>> w’
ans =
5 6 7 8
You can add v and w’ using ordinary vector addition:
>> v + w’
ans =
1.3 Getting help
Actually, the entries of a vector are most easily summed using a builtin MATLAB function called sum. If you are unsure of how to use a MATLAB function or command, you can always type: help followed by the command name, and MATLAB will provide an explanation of how the command works:
>> help sum
SUM Sum of elements. For vectors, SUM(X) is the sum of the elements of X. For matrices, SUM(X) is a row vector with the sum over each column. For N-D arrays, SUM(X) operates along the first non-singleton dimension.
SUM(X,DIM) sums along the dimension DIM.
Example: If X = [0 1 2 3 4 5]
then sum(X,1) is [3 5 7] and sum(X,2) is [ 3 12];
See also PROD, CUMSUM, DIFF.
In general, you can type help in MATLAB and receive a summary of the classes of commands for which help is available. If you are not sure of the command name for which you are looking, there are two other helpful commands. First, typing helpdesk displays the help browser, which is a very helpful tool. Second, if you are interested in commands related to summing, you can type lookfor sum. With this command, MATLAB searches for the specified keyword “sum” in all help entries. This command results in the following:
>> lookfor sum TRACE Sum of diagonal elements. CUMSUM Cumulative sum of elements. SUM Sum of elements. SUMMER Shades of green and yellow colormap. UIRESUME Resume execution of blocked M-file. UIWAIT Block execution and wait for resume. RESUME Resumes paused playback. RESUME Resumes paused recording.
It may take some searching to find precisely the topic and/or command that you are looking for.
1.4 Matrices
MATLAB also works with matrices:
>> A = [1, 2, 3; 4, 5, 6; 7, 8, 0]
A =
1 2 3 4 5 6 7 8 0
>> b = [0; 1; 2]
b =
0 1 2
There are many builtin functions for solving matrix problems. For example, to solve the linear system Ax = b, type A\b:
>> x = A\b
x =
-0.
Note that the solution is printed out to only four decimal places. It is actually stored to about sixteen decimal places. (See Chapter ??.) To see more decimal places, you can type:
>> format long >> x
x =
-0.
Other options include format short e and format long e to display numbers using scientific notation.
1.7 Plotting
Tables and figures are usually more helpful than long strings of numerical results. Suppose you are interested in viewing a plot of cos(50x) for 0 ≤ x ≤ 1. You can create two vectors, one consisting of x-values and the other consisting of corresponding y = cos(50x) values, and use the MATLAB plot command. To plot the values of cos(50x) at x = 0, 0. 1 , 0. 2 ,... , 1, type
>> x = 0:0.1:1; % Form the (row) vector of x values. >> y = cos(50x); % Evaluate cos(50x) at each of the x values. >> plot(x,y) % Plot the result.
Note that the statement x = 0:0.1:1 behaves just like the for loop:
>> for i=1:11, x(i) = 0.1*(i-1); end;
Note also that, unless otherwise specified, each of these statements produces a row vector. In order to produce a column vector, one could replace x(i) in the above for loop by x(i,1), or one could replace the statement in the original code by x = [0:0.1:1]’;. Clearly, this small number of evaluation points will not produce very high resolution, as is seen in the plot produced by MATLAB depicted below.
−1 0 0.2 0.4 0.6 0.8 1
−0.
−0.
−0.
−0.
0
1
The plot command will graph the points (x(1), y(1)), (x(2), y(2)),.. ., which also implies that x and y must be vectors of the same length. We did not use enough points to achieve a high resolution. Therefore, we will change x to include more points and include a title and labels for the axes in the plot with the commands below:
>> x = 0:0.01:1; % Create a vector of 101 x values. >> plot(x,cos(50x)) % Plot x vs cos(50x), without (explicitly) storing cos(50*x). >> title(’Plot of x versus cos(50x)’) >> ylabel(’cos(50x)’) >> xlabel(’x’)
The plot resulting from these commands is:
−1 0 0.2 0.4 0.6 0.8 1
−0.
−0.
−0.
−0.
0
1 Plot of x versus cos(50x)
cos(50x)
x It is also possible to plot more than one function on the same graph. To plot the two functions f (x) = cos(x) and g(x) = x on the same graph, type:
>> plot(x,cos(50*x),x,x)
The result is shown below.
−1 0 0.2 0.4 0.6 0.8 1
−0.
−0.
−0.
−0.
0
1 cos(50x) x
Notice the small boxed legend on the plot. This was added to the plot with the following command:
legend(’cos(50x)’,’x’)
Another way to plot two functions on the same graph is to first plot one, then type hold on, and then plot the other. If you do not type hold on, then the second plot will replace the first, but this command tells MATLAB to keep plots on the screen after they are created. To go back to the default of removing old plots before new ones are added, type hold off. Again, type help plot for more information on plotting or type doc plot which posts the Helpdesk documentation on the plot command. Other useful commands are axis and plot3. For a bit of fun, type the following commands:
>> x = 0:0.001:10; >> comet(x,cos(3*x))
>> x = 0:.5:2; >> display(x) x = 0 0.5000 1.0000 1.5000 2.
In many cases, the extra carriage return imposed by the display command clutters printed results. Therefore, another helpful command is disp, which is similar to the display command.
>> disp(x) 0 0.5000 1.0000 1.5000 2.
You may still wish to have the variable name printed. Concatenating an array of text for output accomplishes this purpose.
>> disp([’x = ’,num2str(x)]) x = 0 0.5 1 1.5 2
For more information, type help num2str. Tables can be created such as the following:
>> disp(’ Score 1 Score 2 Score 3’), disp(rand(5,3)) Score 1 Score 2 Score 3 0.4514 0.3840 0. 0.0439 0.6831 0. 0.0272 0.0928 0. 0.3127 0.0353 0. 0.0129 0.6124 0.
You may find the fprintf command easier to use for tables of results. For instance, consider the simple loop:
>> fprintf(’ x sqrt(x)\n=====================\n’) for i=1:5, fprintf(’%f %f\n’,i,sqrt(i)), end x sqrt(x) ===================== 1.000000 1. 2.000000 1. 3.000000 1. 4.000000 2. 5.000000 2.
The fprintf command takes format specifiers and variables to be printed in those formats. The %f format indicates that a number will be printed in fixed point format in that location of the line, and the \n forces a carriage return after the two quantities i and sqrt(i) are printed. You can specify the total field width and the number of places to be printed after the decimal point by replacing %f by, say, %8.4f to indicate that the entire number is to be printed in 8 spaces, with 4 places printed after the decimal point. You can send your output to a file instead of the screen by typing:
fid = fopen(’sqrt.txt’,’w’); fprintf(fid,’ x sqrt(x)\n=================\n’); for i=1:5, fprintf(fid,’%4.0f %8.4f\n’,i,sqrt(i)); end
which prints the following table in a file called sqrt.txt:
1 1. 2 1. 3 1. 4 2. 5 2.
Again, for more information, refer to MATLAB documentation.
1.10 More loops and conditionals
We have already seen how for loops can be used in MATLAB to execute a set of commands a given number of times. Suppose, instead, that one wishes to execute the commands until some condition is satisfied. For example, one might approximate a root of a given function f(x) by first plotting the function on a coarse scale where one can see the approximate root, then plotting appropriate sections on finer and finer scales until one can identify the root to the precision needed. This can be accomplished with the following MATLAB code:
xmin = input(’ Enter initial xmin: ’); xmax = input(’ Enter initial xmax: ’); tol = input(’ Enter tolerance: ’) while xmax-xmin > tol, x = [xmin:(xmax-xmin)/100:xmax]; y = f(x); plot(x,y) xmin = input(’ Enter new value for xmin: ’); xmax = input(’ Enter new value for xmax: ’); end;
The user looks at each plot to determine a value xmin that is just left of the root and a value xmax that is just right of the root. The next plot then contains only this section, so that closer values xmin and xmax can be determined. In the next chapter we discuss more efficient ways of finding a root of f(x). Another important statement is the conditional if statement. In the above code segment, one might wish to let the user know if the code happens to find a point at which the absolute value of f is less than some other tolerance, say, delta. This could be accomplished by inserting the following lines after the statement y = f(x);:
1.13 More advanced commands
It is perhaps apparent from the reference at the beginning of this chapter to the work on the Mars Exploration Rover, that MATLAB has a large number of commands. As we close this chapter, let us demonstrate some of the graphical capabilities through an example. The commands
[X,Y] = meshgrid(-3:.125:3); Z = peaks(X,Y); meshc(X,Y,Z); axis([-3 3 -3 3 -10 5])
produce the plot:
−3^ −
− 0 1
2 3
−
−
−
0
1
2
−10 3
−
0
5
In order to understand this plot, search MATLAB documentation for the commands meshgrid, peaks, meschc, and axis. While this chapter will get you started using MATLAB, effective use of the MATLAB documentation will be the key to proceeding to more complicated programs.
matlab’s origins
Cleve Moler – is chairman and chief scientist at The MathWorks. In the mid to late 1970s, he was one of the authors of LINPACK and EIS- PACK, Fortran libraries for numerical computing. To give easy access to these libraries to his students at the University of New Mexico, Dr. Moler invented MATLAB. In 1984, he co-founded The MathWorks with Jack Little to commercialize the MATLAB program. Cleve Moler received his bachelor’s degree from Caltech in 1961, and a Ph.D. from Stanford University. Moler was a professor of math and computer science for almost 20 years at the University of Michigan, Stanford University and the University of New Mexico. Before joining The MathWorks full time in 1989, he also worked for Intel Hypercube and Ardent. Dr. Moler was elected to the National Academy of Engineering in 1997. He has received honorary degrees from Link¨oping University, Sweden, the University of Waterloo and the Technical University of Denmark.
Exercises
, v =
, w =
compute the following both by hand and in MATLAB.
(a) vT^ w (b) vwT (c) Av (d) AT^ v (e) AB
(f) BA (g) A^2 (= AA) (h) The vector y for which By = w. (i) The vector x for which Ax = v.