| Introduction | Exercise 1 |
| Matlab files | Exercise 2 |
| Variables | Exercise 3 |
| Variables are Matrices | Exercise 4 |
| Vector Operations | Exercise 5 |
| Flow control | Exercise 6 |
| M-files and graphics | Exercise 7 |
In the last lab, we learned how to start up Matlab and a little bit about using Matlab. I asked you to read a brief excerpt from the Matlab ``Getting Started'' manual that is available on the Web from The Mathworks. This lab is intended as an introduction to using the Matlab language as a programming language. We will not be concerned with many of the details of this language, we will focus on those aspects of the language that make it ideal for numerical calculations.
But Matlab is a programming language and it is important to learn the basics of good programming so that you will be able to function as professionals using Matlab.
This lab will take two sessions. If you print it, you may find the Adobe pdf version more appropriate.
The best way to use Matlab is to use its scripting facility. With sequences of Matlab commands contained in files, it is easy to see what calculations were done to produce a certain result, and it is easy to show that the correct values were used in producing a graph. It is terribly embarrassing to produce a very nice plot that you show to your advisor only to discover later that you cannot reproduce it or anything like it for similar conditions or parameters. When the commands are in clear text files, with easily read, well-commented code, you have a very good idea of how a particular result was obtained. And you will be able to reproduce it and similar calculations as often as you please.
The Matlab comment character is a percent sign (%. That is, lines starting with % are not read as Matlab commands and can contain any text. Similarly, any text on a line following a % can contain textual comments and not Matlab commands.
A Matlab script file is a text file with the extension .m. Matlab script files should always start off with comments that identify the author, the date, and a brief description of the intent of the calculation that the file performs. Matlab script files are invoked by typing their names at the Matlab command line or by using their names inside another Matlab file.
Matlab function files are also text files with the extension .m, but the first non-comment line must start with the word function and be of the form
The key difference between function and script files is that functions are intended to be used repetitively. They can accept parameters and variables used inside a function are invisible outside the function. When I am working on a task, I often start out using script files. As I discover just what tasks are repetitive or when I start to need the same calculation repeated for different parameters, or when I have many intermediate variables that might have the same names as variables in other parts of the calculation, I switch to function files. In these labs, I will specify function file or script file when it is important, and you are free to use what you like when I do not specify.
Because function files are intended to be used multiple times, it is a bad idea to have them print or plot things. Imagine what happens if you have a function that prints just one line of information that you think might be useful, and you put it into a loop that is executed a thousand times. Do you plan to read those lines?
Matlab commands are sometimes terminated with a semicolon (;) and sometimes not. The difference is that the result of a calculation is printed to the screen when there is no semicolon but no printing is done when there is a semicolon. It is a good idea to put semicolons at the ends of all calculational lines in a function file.
Matlab also supports data files. The Matlab save command will cause every variable that Matlab currently knows about to be saved in a file called ``matlab.mat''. You can also name the file with the command save filename that will put everything into a file named ``filename.mat''. This command has many other options, and you can find more about it using the help facility. The inverse of the save command is load.
Note: Matlab function names are
case-sensitive. This means that the function cos is different from
Cos, coS, and COS. File names in Microsoft operating systems,
however, are not strictly case sensitive. To avoid confusion for those
students who might be using Matlab on a Microsoft system, we will
only use lower-case names for Matlab function and script files.
Matlab uses variable names to represent data. A variable name
represents a matrix containing complex double-precision data. Of
course, if you simply tell Matlab x=1, Matlab will understand
that you mean a
matrix and it is smart enough to
print x out without its decimal and imaginary parts, but make
no mistake: they are there. And x can just as easily
turn into a matrix.
A variable can represent some important value in a program, or it can represent some sort of dummy or temporary value. Important quantities should be given names longer than a few letters, and the names should indicate the meaning of the quantity. For example, if you were using Matlab to generate a matrix containing a table of squares of numbers, you might name the table tableOfSquares. (The rule I am using here is that the first part of the variable name should be a noun and it should be lower case. Modifying words follow with upper case letters separating the words. This rule comes from the officially recommended naming of Java variables.)
Once you have used a variable name, it is bad practice to re-use it to mean something else. It is sometimes necessary to do so, however, and the statement
clear firstVariable secondVariableshould be used to clear the two variables firstVariable and secondVariable before they are re-used. This same command is critical if you re-use a variable name but intend it to have smaller dimensions.
Matlab has a few reserved variable names. You should not use these variables in your m-files. If you do use such variables as i or pi, they will lose their special meaning until you clear them. Reserved names include
We said that Matlab treats all its variables as though they were matrices. Important subclasses of matrices include row vectors (matrices with a single row and possibly several columns) and column vectors (matrices with a single column and possibly several rows). One important thing to remember is that you don't have to declare the size of your variable; Matlab decides how big the variable is when you try to put a value in it. The easiest way to define a row vector is to list its values inside of square brackets, and separated by spaces or commas:
rowVector = [ 0, 1, 3, 6, 10 ]The easiest way to define a column vector is to list its values inside of square brackets, separated by semicolons or line breaks.
columnVector1 = [ 0; 1; 3; 6; 10 ]
columnVector2 = [ 0
1
9
36
100 ]
(It is not necessary to line the entries up as I have done, but
it makes it look nicer.)
Matlab has a special notation for generating a set of equally spaced values, which can be useful for plotting and other tasks. The format is:
start : increment : finishor
start : finishin which case the increment is understood to be 1. Both of these expressions result in row vectors. So we could define the even values from 10 to 20 by:
evens = 10 : 2 : 20
Sometimes, you'd prefer to specify the number of items in the list, rather than their spacing. In that case, you can use the linspace function, which has the form
linspace( firstValue, lastValue, numberOfValues )in which case we could generate six even numbers with the command:
evens = linspace ( 10, 20, 6 )or a large number of evenly-spaced points in the interval [10,20] with
points = linspace ( 10, 20, 23 )
Another nice thing about Matlab vector variables is that they are flexible. If you decide you want to add another entry to a vector, it's very easy to do so. To add the value 22 to the end of our evens vector:
evens = [ evens, 22 ]and you could just as easily have inserted a value 8 before the other entries, as well.
Even though the number of elements in a vector can change, Matlab always knows how many there are. You can request this value at any time by using the length function. For instance,
length ( evens )should yield the value 7 (the 6 original values of 10, 12, ... 20, plus the value 22 tacked on later). In the case of matrices with more than one nontrivial dimension, the length function returns the total number of entries. Use the size function in this case. For example, since evens is a row vector, size( evens, 1)=1 and size( evens, 2)=7.
To specify an individual entry, you need to use index notation, which uses round parentheses enclosing the index of an entry. The first element of an array has index 1 (as in Fortran, but not C). Thus, if I want to alter the third element of evens, I could say
evens(3) = 7
plot(meshPoints,sin(2*pi*meshPoints))Please save (export) this plot as a jpeg (.jpg) file and include it with your summary.
% Lab 2, exercise 2 % A sample script file. % Your name and the datefollowed by your name and the date. Follow the header comments with the commands containing exactly the commands you used in the earlier parts of this exercise. Test your script by using clear to clear your results and then execute the script from the command line by typing exer2, by using the ``Run'' button (looks like a sheet of paper with an arrow pointing down) at the top of the edit window, or by using Debug
Matlab provides a large assembly of tools for matrix and vector manipulation. We will investigate a few of these by trying them out.
rowVec1 = [ -1 -4 -9]
colVec1 = [ 2
4
8 ]
mat1 = [ 1 3 5
7 9 2
4 6 8 ]
colVec2 = (pi/4) * colVec1
colVec2 = cos( colVec2 )Note that the values of colVec2 have been overwritten. Are these the values you expect?
colVec3 = colVec1 + colVec2
illegal = colVec1 + rowVec1;Look carefully at the error message. You must recognize from the message what went wrong when you see it in the future.
colvec4 = mat1 * colVec1
mat1Transpose = mat1' rowVec2 = colVec3'Warning: The single quote really means the complex-conjugate transpose (or Hermitian adjoint). If you want a true transpose applied to a complex matrix you must use ``
.'''.
mat2 = mat1 * mat1' % symmetric matrix rowVec3 = rowVec1 * mat1 dotProduct = colVec3' * colVec1 euclideanNorm = sqrt(colVec2' * colVec2)
determinant = det( mat1 ) tr = trace( mat1 )
min(rowVec1)
max(mat1)
max(abs(rowVec1))
A=magic(100); % please do not print all 10,000 entries.then the largest and smallest row sums, the largest and smallest column sums, and the sums of the two diagonals are all the same.
Hints:
integers = 0 : 10but now we'll get an error when we try to multiply the entries of integers by themselves.
squareIntegers = integers * integers
Realize that Matlab deals with vectors, and the default multiplication operation with vectors is vector multiplication. In order to do element-by-element multiplication, we need to place a period in front of the operator:
squareIntegers = integers .* integers
Now we can define cubeIntegers and fourthIntegers in a similar way.
cubeIntegers = squareIntegers .* integers fourthIntegers = squareIntegers .* squareIntegers
Finally, we would like to print them out as a table. integers, squareIntegers, etc. are row vectors, so make a matrix whose columns consist of these vectors and allow Matlab to print out the whole matrix at once.
tableOfPowers=[integers', squareIntegers', cubeIntegers', fourthIntegers']
squareIntegers = integers .^ 2These problems never come up with addition or subtraction; nor do they occur with division or multiplication by a scalar.
tableOfCubes = tableOfPowers(:,[1,3]) tableOfOddCubes = tableOfPowers(2:2:end,[1,3]) tableOfEvenFourths = tableOfPowers(1:2:end,1:3:4)
A = magic(10)What commands would be needed to generate the four
It is critical to be able to ask questions and to perform repetitive calculations in m-files. These topics are examples of ``flow control'' constructs in programming languages. Matlab provides two basic looping (repetition) constructs: for and while, and the if construct for asking questions. These statements each surround several Matlab statements with for, while or if at the top and end at the bottom.
Note: It is an excellent idea to indent the statements between
the for, while, or if lines and the end line.
This indentation strategy makes code immensely more readable.
Your m-files will be expected to follow this convention.
The syntax of a for loop is
| for control-variable=start : increment : end |
| Matlab statement ... |
| ... |
| end |
The syntax of a while loop is
| Matlab statement initializing a control variable |
| while logical condition involving the control variable |
| Matlab statement ... |
| ... |
| Matlab statement changing the control variable |
| end |
The syntax of a simple if statement is
| if logical condition |
| Matlab statement ... |
| ... |
| end |
The syntax of a compound if statement is
| if logical condition |
| Matlab statement ... |
| ... |
| elseif logical condition |
| ... |
| else |
| ... |
| end |
Note that elseif is one word! Using two words else if changes the statement into two nested if statements with possibly a very different meaning, and a different number of end statements.
The following Matlab code computes the trapezoid rule for the
case that
,
and
.
% Use the trapezoid rule to approximate the integral from 0 to 1
% of exp(x), using N (=10) intervals
% Your name and the date
N=10;
h=1/(N-1);
x=-h; % look at this trick
approxIntegral=0.;
for k=1:N
% compute current x value
x=x+h;
% add the terms up
if k==1 | k==N
approxIntegral=approxIntegral+(h/2)*exp(x); % ends of interval
else
approxIntegral=approxIntegral+h*exp(x); % middle of interval
end
end
approxIntegral=approxIntegral+(h/2)*exp(x); % ends of interval
approxIntegral=approxIntegral+h*exp(x); % middle of interval
If you have to type everything at the command line, you will not get very far. You need some sort of scripting capability to save the trouble of typing, to make editing easier, and to provide a record of what you have done. You also need the capability of making functions or your scripts will become too long to maintain. In this section we will consider first a script file and later a function m-file. We will be using graphics in the script file, so you can pick up how graphics can be used in our work.
The Fourier series for the function
on the interval
is
% compute NTERMS terms of the Fourier Series for y=x^3 % plot the result using NPOINTS points from -1 to 1. % Your name and the date NTERMS=10; NPOINTS=300; x=linspace(-1,1,NPOINTS); y=zeros(size(x)); for k=1:NTERMS y=y-2*(-1)^k*(pi^2/k-6/k^3)*sin(k*x); end plot(x,y); hold on plot(x,x.^3,'g'); axis([-1,1,-2,2]); hold offIt is always good programming practice to define constants symbolically at the beginning of a program and then to use the symbols within the program. Sometimes these special constants are called ``magic numbers.'' By convention, symbolic constants are named using all upper case.
y=zeros(size(x));do? You can use Matlab help for zeros and size for more information.
Note: The command hold is actually a ``toggle.'' Each time it is used, it switches from ``on'' to ``off'' or from ``off'' to ``on.'' Using it that way is easier but you have to remember which state you are in.
In the following exercise you
are going to modify the calculation so that it continues so
long as the difference between the partial sum and the
function
is pretty small, say 0.1. The while
statement is designed for this case. It would be used in
the following way. (The ellipses represent lines of code
that are unchanged from above.)
TOLERANCE=0.1; % the chosen tolerance value
...
k=0;
difference=TOLERANCE+1; % bigger than TOLERANCE
while difference > TOLERANCE
k = k + 1;
...
difference = max( abs( x.^3 - y ) );
end
disp( strcat('Number of iterations =',num2str(k)) )
difference=TOLERANCE+1;
k = k + 1;
The next task is to make a function m-file out of exer6.m in such a way that it takes as argument the desired tolerance and returns the number of iterations required to meet that tolerance.
function k = exer7( tolerance ) % k = exer7( tolerance ) % more comments % Your name and the date
exer7(0.1)and it will assign the value if it is invoked on the right of an equal sign:
numItsRequired=exer7(0.1)
Back to MATH2070 page.