Beginning Matlab Exercises, Exercises of Mathematics

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

2021/2022

Uploaded on 02/11/2022

zeb
zeb 🇺🇸

4.6

(27)

231 documents

1 / 13

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Beginning Matlab Exercises
R. J. Braun
Department of Mathematical Sciences
University of Delaware
1 Introduction
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. htextiwill 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!
2 Getting Started
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 <enter> will start Matlab using its
window manager. In this mode, you can find helpful pull down menus across the top of the window (or
desktop). The default configuration has one main command window, and two other windows that allow
access to the workspace, command history, current directory and launch pad.
Typing the command matlab -nojvm runs Matlab without the window manager. This can avoid some
annoying bugs in the window manager that may appear (particularly in linux) on starting up. This will give
only the command window; plots will appear in separate graphics windows in both modes.
To exit, use the pull down menu under File or type the command exit in the command window.
3 Scalar arithmetic
Matlab can be used as a calculator. Some of the problems indicate the precedence of arithmetic operations.
1. 3*2^4
2. (3*2)^4 % parentheses have highest priority
3. 3-2^4
4. 3^4-3
5. 8/2^4
6. 2^4\8 % same as previous! two different divisions, \ and /
7. 8^4/2
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.
4 Vectors
It will typically be that our basic unit for computing will be a vector. We need to be able to create and
manipulate them.
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Beginning Matlab Exercises and more Exercises Mathematics in PDF only on Docsity!

Beginning Matlab Exercises

R. J. Braun

Department of Mathematical Sciences

University of Delaware

1 Introduction

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!

2 Getting Started

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 will start Matlab using its window manager. In this mode, you can find helpful pull down menus across the top of the window (or desktop). The default configuration has one main command window, and two other windows that allow access to the workspace, command history, current directory and launch pad. Typing the command matlab -nojvm runs Matlab without the window manager. This can avoid some annoying bugs in the window manager that may appear (particularly in linux) on starting up. This will give only the command window; plots will appear in separate graphics windows in both modes. To exit, use the pull down menu under File or type the command exit in the command window.

3 Scalar arithmetic

Matlab can be used as a calculator. Some of the problems indicate the precedence of arithmetic operations.

  1. 3*2^
  2. (3*2)^4 % parentheses have highest priority
  3. 3-2^
  4. 3^4-
  5. 8/2^
  6. 2^4\8 % same as previous! two different divisions, \ and /
  7. 8^4/

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.

4 Vectors

It will typically be that our basic unit for computing will be a vector. We need to be able to create and manipulate them.

4.1 Creating vectors

  1. x = [3 4 7 11] % create a row vector (spaces)
  2. x = 3:8 % colon generates list; default stride 1
  3. x = 8:-1:0 % 〈start〉 : 〈stride〉 : 〈stop〉 specifies list
  4. xx = [ 8 7 6 5 4 3 2 1 0]; % same as last; semicolon suppresses output
  5. xx % display contents
  6. x = linspace(0,1,11) % generate vector automatically
  7. x = 0:0.1:1 % same thing
  8. y = linspace(0,1); % note semicolon!
  9. length(x)
  10. length(y)
  11. size(x)
  12. size(y)
  13. y(3) % access single element
  14. y(1:12) % access first twelve elements
  15. y([3 6 9 12]) % access values specified in a vector!
  16. x’ % transpose
  17. z = [ 1+2i 4-3i ]
  18. z’
  19. z.’ % note difference in transposes!
  20. 3*[1 2 5] % factor replicated, multiplies each element

Matlab labels the arrays (vectors and matrices) beginning with 1; this will be an important programming detail on more than one occasion.

4.2 Help with vectors and other things

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.

  1. help help % try Matlab’s extensive help
  2. help length
  3. help size
  4. help linspace
  5. help logspace
  6. help clc
  7. help clear
  8. help who

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.

  1. diary ThisClassIsGreat % puts diary in file called ThisClassIsGreat
  2. g*h
  3. e*f
  4. diary off % diary file closed
  5. diary ThisClassIsGreat % reopening it will append additional work
  6. f*e
  7. diary % diary toggles with no additional specification

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.

7.1 Basic output

  1. disp(’The disp command writes text.’) % inside quotes: verbatim
  2. t = logspace(-3,6,10);
  3. x = 0.1234567890123456*t;
  4. format short
  5. t
  6. x
  7. format long
  8. x
  9. format long e
  10. x
  11. format short e
  12. x
  13. format short g
  14. x
  15. format long g
  16. x
  17. disp(sprintf(’The 10th element of x is x(10) = %6.3f’,x(10)))
  1. disp(sprintf(’The 10th element of x is x(10) = %10.3f’,x(10)))
  2. disp(sprintf(’The 10th element of x is x(10) = %12.3f’,x(10)))
  3. disp(sprintf(’The 10th element of x is x(10) = %8.3e’,x(10)))
  4. disp(sprintf(’The 10th element of x is x(10) = %8.3e’,x(10)))
  5. disp(sprintf(’The 10th element of x is x(10) = %8.12e’,x(10)))
  6. disp(sprintf(’The 10th element of x is x(10) = %24.15e’,x(10)))
  7. disp(sprintf(’The 10th element of x is x(10) = %1.4g’,x(10)))
  8. disp(sprintf(’The 10th element of x is x(10) = %16.12g’,x(10)))
  9. disp(sprintf(’The 10th element of x is x(10) = %24.15g’,x(10)))

7.2 Repeating Commands I

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

  1. % for loop now

for k = 1: disp(sprintf(’%8.5e’,x(k))) end

  1. % for loop doing a calculation

total = 0 for k = 1: total = total + x(k); disp(sprintf(’Total for k=%2.0f is %15.8g’,k,sum)) end

  1. sum(x) % built in matlab command sums components of vector

Here the command sum can replace the loop; it adds up the elements of a vector.

7.3 Creating a table

  1. Try this script to make a neat table.

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.

  1. eye(4) % Identity matrix
  2. eye(2,4)
  3. eye(4,2)
  4. rand(3) % Random elements uniformly distributed between 0 and 1
  5. b = eye(3)
  6. rand(size(b))
  7. a = 1:
  8. diag(a)
  9. diag(a,1)
  10. diag(a,-2)

8.3 More about creating arrays

  1. d = exp(1)
  2. d*ones(3,4) % slowest
  3. d+zeros(3,4) % slow
  4. d(ones(3,4)) % faster
  5. repmat(d,3,4) % fastest

8.4 Selecting and changing parts of matrices

  1. g = [1 2 3 4; 5 6 7 8; 9 10 11 12]
  2. g(3,2) % single element
  3. g(:,2) % all rows, second column
  4. g(2,:) % second row, all columns
  5. g(1:2,:)
  6. g(2,:) = [1 1 1 1] % replace row
  7. g(:,2) = [2; 2; 2] % replace column

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.

  1. A = rand(5) % matrix of coefficients from Ax=b
  2. b = rand(5,1) % right hand side
  3. det(A) % determinant of A
  4. inv(A) % inverse of A
  5. x = inv(A)*b % solves system, NOT recommended!
  1. size(x), size(b), size(A)
  2. x2 = A\b % better way to solve systems
  3. spy(A) % sparsity plot: show nonzero elements
  4. D = diag(1:5)
  5. spy(D)
  6. L = tril(A)
  7. U = triu(A)
  8. size(U), spy(U)

10 More vectors and plotting

10.1 Vectorizing function evaluations

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.

  1. We could plot the function as follows; I recommend opening the editor in matlab and typing this into the editor and saving the file. The resulting script file can be run in Matlab by typing the filename without the extension .m to the command window prompt. The first approach is:

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.

  1. Now make use of vectorization and try to minimize the amount of calculation of powers of x; you may type this in by modifying your previous script file, or download this script from the course web page. In this case, we

% 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;

  1. a = 4; b = -1; c = 1;
  2. a > b % note that the output is a logical value
  3. a < b
  4. a >= b
  5. mytest = (abs(b) == c) % parentheses optional but clearer Things get a little more complicated with arrays. Using the g and h from above, try out the following.
  6. g = [1 2 3 4; 5 6 7 8; 9 10 11 12]
  7. h = [3 3 4 4; 5 5 6 6; 7 7 8 8]
  8. h >= g
  9. g == h % note that the output is a logical value
  10. bigger = (g >= h)
  11. g(bigger)
  12. g([0 0 0 1; 1 1 1 1; 1 1 1 1]) % array argument not logical!

We will use some of this kind of thing programming later, but I don’t want to elaborate now.

11.3 Logical operators

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.

  1. h >= g
  2. p = ~(h >= g)
  3. ~p
  4. (g == h) & (g > h)
  5. (g == h) | (g > h)
  6. g >= h

11.4 The while loop

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 end

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.

11.5 The if-else-end construct

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 end

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 else end

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 elseif

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.