This tutorial is designed to reacquaint you with the MATLAB ideas initially presented by Tom Huber at the Envision It! workshop held at Arlington High School in late January. My hope is that this material will prove to be good preparation for Tom's follow up workshop on April 12th.
Most of the material in this tutorial is derived from the worksheets presented at the January workshops. These documents can be accessed directly by visiting Tom's homepage at Gustavus Adolphus College. Check under the Envision It! item.
A matrix is simply a rectangular list of numbers. The "size" of a matrix is given as two numbers, the first is traditionally the number of rows in the matrix while the second is the number of columns in the matrix. Matrices are usually written in tabular form contained between two large parentheses or square brackets.
For example, the matrix below is a 2x3 (this size is read "two by
three") matrix without the enclosing parenteses or brackets.
34 56 31 -45 6 43
Arrays, sometimes called vectors, are special cases of matrices, namely arrays have a single row or a single column of numbers. Arrays with a single row of numbers are called row vectors to contrast them with column vectors. Only one subscript is needed to reference a particular entry in an array.
To create a matrix and assign it a name within the MATLAB program simply fire up MATLAB and at the prompt enter the matrix's name, an equal sign (=), and an open bracket ([). Next enter the numbers, separated by either commas or blank spaces, which make up the first row of the matrix. If your matrix has only one row, type in the close bracket (]) and hit RETURN. If you have several rows to enter, signify the end of each row with a semicolon before proceeding to enter the values for the next row. (No semicolon is necessary after the last row.) When you have finished entering all the entries of the matrix type a close bracket and hit RETURN. Your matrix should appear on the screen.
As an example, consider the 2x3 matrix given above. To give this matrix the name A we would enter the following at the MATLAB prompt:
A = [ 34 56 31; -45 6 43 ]
MATLAB includes a command which returns the size of an array or matrix. The command is the size command. It returns a row vector whose first entry is the number of rows in the argument and whose second entry is the number of columns.
As an example the command
size(A)would return the vector [2 3] if A is the matrix defined in the example above.
Many special matrices appear so frequently that the designers of MATLAB have created shortcuts for creating them.
temp = zeros(10)will do the trick.
To create a non-square matrix (including vectors) consisting of all zeros it is necessary to use a second version of the command. This version takes two arguments, the number of rows and the number of columns in the matrix being created. For example, to create a 3x5 matrix of all zeros, the command
many0 = zeros(3,5)could be used.
lonely = ones(1,5)
ident = eye(5)creates the 5x5 identity matrix.
diagmatrix = diag([1 2 3])
test = 0:4:20would create the row vector [0 4 8 12 16 20] and names it test. The first entry in the vector is given by the first entry in the command, the second entry in the command gives the interval between entries (a.k.a. the stepsize), 4 in this case. The last entry tells the process when to stop, at 20 in this example. To create a column vector, simply use the MATLAB transpose operator, the apostrophe ('). If x is a row vector, the notation x' signifies a column vector whose entries are identical to those of x. A similar transformation occurs if you begin with a column vector. Thus the above becomes
test = [0:4:20]'(note that without the square brackets you would be transposing only the scalar 20 not the entire vector!)
If only two numbers are given, e.g. 1:10, MATLAB assumes the stepsize is 1. Negative step sizes are allowed (as long as the end is less than the beginning!)
Compare the above output to the result of
test = linspace(0,20,6)which uses the number of elements desired as an input argument.
In some of these examples you may have been overwhelmed with output after you entered the command. One nice MATLAB trick is to suppress the printed output by ending any command with a semicolon. Compare the result of the following two commands
a1 = zeros(100) a2 = zeros(100);
MATLAB's power is in its ability to perform matrix arithmetic very efficiently. MATLAB divides its matrix arithmetic into two varieties. First there are componentwise operations in which the indicated operation is performed on two matrices of exactly the same size and the resulting matrix is also of this common size. The entries in the resulting matrix are calculated by performing the operation on entries occupied the same position within each matrix.
The second type of matrix arithemetic is the more traditional type of matrix multiplication and exponentiation taught in high school and college algebra classes.
Aside from operations on pairs of matrices, MATLAB also allows for operations on a matrix and a scalar, which are non-standard but intuitive.
In the sections below we cover each of these types of arithmetic operations.
There are four scalar operations, addition, subtraction, multiplication and division, denoted by the symbols + - * and / respectively. In each case the indicated operation is performed on each entry in the matrix.
As an example, consider the two MATLAB commands shown below:
fdj = [ 1 2 3;5 4 3; 6 5 8 ]; abc = 3*fdjThe matrix abc contains entries created by multiplying each of the corresponding entries of fdj by 3.
MATLAB's componentwise matrix addition and subtraction matches the traditional form of the same operations. For two matrices to be added or subtracted they must be of the same size. When two matrices are added the resulting matrix is of the same size as the original matrices. The entries are computed by adding or subtracting the corresponding entries in the two original matrices. This addition or subtraction is indicated to MATLAB by placing a + or - sign between two matrices. For example, the MATLAB commands:
abc = [1 2;3 4] def = abc - [6 -1; 2 0]would print out the square matrix with -5 and 3 in the first row and 1 and 4 in the second row. This new matrix would be given the name def.
For example, the three MATLAB commands:
abc = [1 2 3; 4 5 6]; def = [1 2 1; -1 3 -2]; abc.*defcreate a matrix whose first row has entries 1, 4 and 3. The second row has entries -4, 15 and -12.
Note that MATLAB does NOT use the asterisk to denote this componentwise multiplication. The asterisk, by itself, represents the more traditional form of matrix multiplication. To indicate componentwise multiplication MATLAB uses the dot-star notation, namely a period followed immediately by an asterisk.
The same idea holds for componentwise division. The MATLAB symbol for this is dot-slash (./).
MATLAB uses the dot-carat (.^) to signify componentwise exponentiation. The exponent is a scalar and the .^ operation simply means to raise each entry in the matrix to the indicated power. For example,
abc = [1 2;3 4]; abc.^2would print out a 2x2 matrix whose entries were 1, 4, 9 and 16.
fdj+3 fdj-6 fdj/2in each case the indicated operation should be performed on each entry of the matrix fdj.
abc = 1:10; def = 5:14; ghi = 3*abc + def
abc = [1 2 3 4;5 6 7 8]; def = [4 3 2 1;8 7 6 5]; abc + def
tut1 .* tut2 tut2 .* tut1 tut1 ./ tut2 tut2 ./ tut1 tut1 .^ 2
The symbol MATLAB uses to indicate traditional matrix multiplication is the asterisk without a dot.
tut1 * tut2 tut2 * tut1 tut1 * tut2' tut2' * tut1 tut1 ^ 2 (tut2' * tut1)^2
x*ones(1,123)'which multiplies the vector x with the column (after the transpose) vector made up of 123 ones.
To explore this technique create a row vector with 10 entries, and use the idea above to direct MATLAB to compute the sum of the entries.
MATLAB supports a large suite of functions, including the usual trigonometry functions as well as functions designed specifically for matrices, such as the matrix inverse function.
Most of the functions we will use are functions which are often applied to single numbers when used outside the context of MATLAB. An example would be the sine trigonometric function. When applied to a matrix in MATLAB these functions perform in a componentwise fashion. As an example, consider the matrix
nums=[0 5*pi/6 pi/2; pi/6 pi 2*pi]The command
sin(nums)would return the 2x3 matrix whose first row is 0, 0.5 and 1 while the second row is 0.5, 0 and 0.
To create two dimensional graphs of functions or other data, it is necessary to create two row vectors which contain the x and y coordinates, respectively, of the points to be plotted. MATLAB plot command connects the points indicated by these coordinates with a series of straight lines.
For example, the following three MATLAB commands generate a unit square whose lower left hand corner is the origin.
x = [ 0 1 1 0 0]; y = [ 0 0 1 1 0]; plot(x,y)While the physical drawing of the square occurs too quickly to watch, MATLAB begins at the origin and draws the square in the direction indicated by the points, in this case counterclockwise.
More traditional mathematical graphs can be created by first defining
the range of x values over which you want to graph and then
creating a vector which contains a good number of values in this
x range. For example, to create a graph of the function
y = sin(x)*cos(x)^2
over the range -2*pi to 2*pi, we could enter the following MATLAB commands:
x = -2*pi:0.1:2*pi; y = sin(x).*cos(x).^2; plot(x,y)Note the componentwise arithmetic here. This is critical to the proper functioning of the plot command.
It is possible to place more than one graph on a single plot. The MATLAB commands below plot both the sine and cosine curve on the same plot.
x=-2*pi:0.1:2*pi; y=sin(x); z=cos(x); plot(x,y,x,z);You can add additional plots by using the hold command.
hold on plot(x,exp(x),'--') hold offNotice that we changed the line style to dashed. See help plot for other plot options.
theta = 0 : 0.05 : 2*pi; hold on axis('square') plot(cos(theta),sin(theta))When you are finished using the image, type hold off. To see the effect of the axis('square') statement, enter the MATLAB command axis('normal') and redraw the graph.
theta = 0 : 0.1 : 2*pi; r = sin(3*theta); plot(r .* cos(theta), r .* sin(theta))Note the componentwise multiplication used in this problem, indicated by the dot-asterisk (.*) notation.
As an optional exercise guess what happens if the sin(3*t) term is changed to sin(4*t). Then test your guess by creating the graph.
To create a 3-D graph we need to create three matrices. The first gives the x coordinates, the second gives the y coordinates and the third gives the z coordinates.
These matrices can be created in a series of steps. As an example,
let's consider the graph of the function
z = (2 sin(3x))/( (x^2+2)(y^2+1) ).
for values of x and y between -3 and 3.
The steps for achieving this are:
The following MATLAB commands carry out these three steps for the example we are considering.
x = -3:0.2:3; y = -3:0.2:3; [X Y] = meshgrid(x,y); Z = 2*sin(3*X)./( (X.^2 + 2).*(Y.^2 + 1) ); surf(X,Y,Z)Try these out for yourself and see the results. Note how the formula for Z is related to the mathematics with which we started. See if you can explain why each period in the Z formula must be there.
If you prefer contour maps to surface maps, try the contour command:
contour(X,Y,Z)and a graph of the contour lines for the function will appear.