







Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A collection of exercises intended to help students start learning Matlab, a powerful package with many capabilities that is easy to use on many levels. It covers getting started, scalar arithmetic, help with vectors and other things, functions and plotting, reserved words, diary files, repeating commands, vector and matrix arithmetic, standard arrays, matrix algebra, conditional execution and repeating commands, and references.
Typology: Exercises
1 / 13
This page cannot be seen from the preview
Don't miss anything!








This collection of exercises is intended to help you start learning Matlab. Matlab is a huge package with many capabilities, but it is easy to use on many levels. The text indicated by the numbers will be Matlab commands that you can input to the Matlab prompt. 〈text〉 will indicate quantities that you need to replace with in a Matlab command. Text to the right of a % symbol are comments and need not be typed at the prompt unless you wish to have the comment in a diary or other file. In nearly all cases, no output will be shown; that’s for you to find!
In the computer classroom, you can start Matlab by opening a terminal window and then typing the appropriate command. Typing the command matlab followed by
Matlab can be used as a calculator. Some of the problems indicate the precedence of arithmetic operations.
Precedence of arithmetic operations is: (1) parentheses, (2) exponentiation, (3) multiplication and di- vision, and (4) addition and subtraction. Calculations proceed from left to right on the line and equal precedence is settled in this way.
It will typically be that our basic unit for computing will be a vector. We need to be able to create and manipulate them.
Matlab labels the arrays (vectors and matrices) beginning with 1; this will be an important programming detail on more than one occasion.
Matlab has extensive online help; try these commands to get help at the command line. If the window manager is running in Matlab, you can also get browser-based interactive help. Try both.
6 Diary files
We can record what was typed and the text-based output during a Matlab session in a file called a diary file. This recording of a session will be useful for homework and projects. It is not a program and the Matlab commands can’t be run in the desktop like a script file can.
7 Output
We will have the need to produce legible output; let’s see how to do that. First, we will do some very basic output commands; then, we need to see how to repeat commands in Matlab. Finally, we will do a little nicer output.
The for loop repeats the commands that are inside of it. The basic structure is
for <list-of-values> <statements-to-be-done> end
Use this structure to repeat output, or do calculations
for k = 1: disp(sprintf(’%8.5e’,x(k))) end
total = 0 for k = 1: total = total + x(k); disp(sprintf(’Total for k=%2.0f is %15.8g’,k,sum)) end
Here the command sum can replace the loop; it adds up the elements of a vector.
disp(’ ’) % a blank line disp(’ k t x ’) disp(’----------------------------’) for k=1: disp(sprintf(’%2.0f %7.3g %7.7e’,k,t(k),x(k))) end
8 More about working with vectors and matrices
We need more tools to efficiently manipulate vectors and matrices in Matlab.
9 A start at matrix algebra
In linear algebra, there was a need to solve systems, find determinants and inverses, and to construct special matrices; we now scratch the surface of these capabilities in Matlab.
10 More vectors and plotting
We try a different rational function than in your textbook. The ideas behind rational functions approxima- tions are discussed in Numerical Analysis by Burden and Faires (Section 8.4), which is on reserve for this course. (Maple can compute the rational function approximation with the ratpoly command.) Consider the rational function
y =
1 − 35 x + 203 x^2 − 601 x^3 1 + 25 x + 201 x^2
which approximates e−x^ on the interval x ∈ [0, 1]. We want to implement this function for plotting and to compare with the exponential function.
n = 150; x = linspace(0,1,n); y = zeros(1,n); for k = 1:n y(k) = (1-(3/5)x(k)+(3/20)x(k)^2 -(x(k)/60)x(k)^2)/... (1+(2/5)x(k)+(1/20)*x(k)^2) end plot(x,y) xlabel(’x’), ylabel(’y’); title(’Rational function approximation to e^{-x}’)
This approach makes no use of vectorization; the for loop computes each element one at a time. Note that x^2 is computed several times.
% Script file: RatFunPlot % Compare rational function approximation to exp(-x) on [0,1] % f(x) = (1-3x/3-3x^2/20-x^3/60)/(1+2x/5+x^2/20) % n = 150;
We will use some of this kind of thing programming later, but I don’t want to elaborate now.
We can string relational operators together and manipulate logical variables using logical operators. They are (Matlab in parentheses): logical AND (&), logical OR (|) and logical NOT (∼). The NOT operator just changes the value of the logical variable to the other value. A truth table shows what the AND and OR operators do; it will be given in class. The upshot is that the both parts from an AND operator must be True to return a True; only one of the inputs for the OR operator need be True for it to return True. Continuing with the last set of Matlab commands, try these out.
Sometimes, we want to repeat commands until a condition is satisfied. If we don’t know how many repetitions are required in advance, a while loop is preferable over a for loop. The general structure is
while
The 〈commands〉 inside the while loop will be repeated as long as the 〈expression〉 returns a value of True, provided that 〈expression〉 returns a scalar. If the 〈expression〉 evaluates to an array, then all of the values that result from it must be True for 〈commands〉 to be evaluated. An example follows; it could be typed into a script file or at the command prompt. In the example, we halve a number until it is so small that the computer can’t detect it when added to 1; the last number before this occurs is called machine epsilon and we’ll talk about it more in class.
num = 0; myeps = 1; while (1+myeps) > 1 myeps = myeps/2; num = num + 1; end num myeps = 2*myeps eps % matlab’s preset variable for machine epsilon
The result is that myeps = eps = 2−^52.
Sometimes we want to compute one set of commands or another depending on the result of a relational test. There are several forms that this sort of construct can take.
11.5.1 Simplest
The simplest is:
if
An example follows; given a positive number of pens, a cost is computed and displayed.
if (pens >= 0) cost = pens*1.99; disp(sprintf(’Cost of %3.0f pens is $ %5.2f’,pens,cost)) end
11.5.2 Intermediate
The next most complicated is:
if
The example now prints a warning for negative numbers of pens.
if (pens >= 0) cost = pens*1.99; disp(sprintf(’Cost of %3.0f pens is $ %5.2f’,pens,cost)) else disp(’An invalid number of pens was specified.’) end
11.5.3 Most general
The most general form is:
if
References
[1] D. Hanselman and B. Littlefield, Mastering Matlab 6, (Prentice Hall, Upper Saddle River, 2001).
[2] D. Hanselman and B. Littlefield, Mastering Matlab 7, (Prentice Hall, Upper Saddle River, 2004).
[3] D.J. Higham and N.J. Higham, Matlab Guide, (SIAM, Philadelphia, 2005, 2nd edn.). (Matlab 6 version available.)
[4] W.J. Palm III, Introduction to Matlab 7 for Engineers, (McGraw-Hill, New York, 2005). (Matlab 6 version available.)
[5] R. Pratap, Getting Started with Matlab 7, (University Press, Oxford, 2005).
[6] A. Gilat, Matlab: An Introduction with Applications, (Wiley, New York, 2003). This book is based on Matlab 6, but is still a friendly introduction.
[7] C. Van Loan, Introduction to Scientific Computing, (Prentice Hall, Upper Saddle River, 2000). The opening two chapters are a great introduction to Matlab.