CS100 Fall 1998

Matlab Hints

Introductory Comments: This handout summarizes some helpful features of the Matlab language. You may wish to consult it as you do Assignment 7. Some of this is review of concepts you have already seen. The main focus is on how to create and manipulate one and two dimensional arrays in Matlab. We have included examples that should help you learn the concepts quickly.

If you have purchased the book by Pratap we recommend that you work through the tutorials in the first two chapters. These are fairly quick and very well designed. Chapter 3 is a good source of information on arrays. If you purchased the book by Hanselman and Littlefield, look at chpaters 1-4. There is a lot more there than you need to know, so just pick out the relevant material.

Matlab help: Matlab comes with fairly extensive online help, which can serve as an additional source of information. Typing help elfun and help ops will give you a list of some basic commands. Typing help followed by the name of a command will give information about that command. For example, help help gives information about the help command. Note: When you use the help command, you will notice that any function names and variables are capitalized in the response that appears on your screen. All of these functions actually have names that are in lower case. So you must type their names in lower case letters when you use them, e.g. use the name sum rather than SUM.

Another potentially useful command is the lookfor command; this will search the list of commands and return those commands which include a particular word in their description. For example, we could search for all the functions which involve a cosine:

» lookfor cosine

ACOS Inverse cosine.

ACOSH Inverse hyperbolic cosine.

COS Cosine.

COSH Hyperbolic cosine.

TFFUNC time and frequency domain versions of a cosine modulated Gaussian pulse.

 

I. General Overview of Matlab

Types: The basic type in Matlab is arrays of complex numbers. So, an integer value or variable is really just a 1x1 array containing the integer value. A one-dimensional array is called a vector, a two-dimensional array is called a matrix, and a single number (an integer, real number, or complex number) is called a scalar. A scalar is really just an array with one row and one column, but it is treated just as we treat numerical values in Java. This is common terminology, so you will find it used in most books on Matlab. In this handout and in the texts on Matlab the term matrix is also often used loosely to refer to either one or two dimensional arrays. Because the complex numbers are built into the Matlab environment we can work with them easily. But you do not need to think in terms of complex numbers or use them at all unless you want to.

Operations and Functions: There are many built-in operations and functions. Here are just a few.

• For complex (and real) numbers we have the usual operations of +, -, *, /, and ^ The symbol ^ means exponentiation.

• Typical functions are sin, cos, log, sqrt, log10, round, etc.

• Variables are created by just assigning them values. For example, if the variable x has not already been defined, the command

>> x = 5

creates a new variable called x and initializes it to the value 5. If x already exists it simply assigns the variable the new value 5 instead.

• As in Java, we have built-in relational operators and operators for boolean valued expressions. <, <=, > >=, == are used as in Java. The symbol for "does not equal" is ~= (the tilde symbol followed by an equals sign). The symbols for AND, OR, NOT are &, |, ~ . Matlab also has the symbol xor for the operation of EXCLUSIVE OR. The expression p xor q is true whenever p is true or q is true but they are not both true. That is, p xor q has the same meaning as the expression (p | q) & ~ ( p & q) .

In Matlab, there is no type bool. Instead, 0 is equivalent to false and 1 is equivalent to true. We determine whether 0 and 1 are to be treated as truth values or as numbers by looking at the context in which they appear. For example, the statement

>> x = (3 > 5)

assigns the value 0 to x. More generally, any number that is not equal to zero is evaluated as true in a context in which it is used as a boolean value. For example, x = ~3 assigns x the value 0, since 3 is treated as having value true, so ~3 is false. (This may seem a bit strange, but it is common in languages such as Matlab and C, and can be useful in some cases.)

Entering commands: As you have already seen, you can type in either an expression or a command by the prompt symbol » in the command window. If you type in an expression it evaluates the expression and prints the result in the window. If you type in a command such as an assignment statement it carries out the assignment and then displays the value that was assigned. If the line typed has a semi-colon at the end of it, then no value is displayed. If you typed in a graphics command the command is executed in a graphics window. If you cannot fit a command all on one line type 3 dots (...) before hitting the return and continue on the next line. When you use the 3 dots Matlab treats your command as if it were all on one line, ignoring the return. All of these facts apply to expressions and commands typed into a script or function file as well.

Examples:

>> a = 5

5

>> 2*a

10

>> b = 7;

>> c = a + b

12

>> b

7

II. Using Arrays in Matlab

The real power of Matlab becomes apparent when you see how easy it is to do operations on arrays. As we show you some of these operations, think about how you would implement them in a programming language like Java.

Some useful features:

• Matrix variables are dynamically managed in Matlab. This means we can add or delete rows and columns in a matrix.

• Because type matrix is the basic type in Matlab there are many built-in operations and functions that can be applied to them.

Defining a Matrix or Vector Variable: The easiest way to define an array variable is to assign it a list of values, using square brackets.

Examples:

>> A = [10 15 20] ;

>> B = [1; 2; 3];

>> C = [1

2

3];

This creates a row vector called A that contains the values 10, 15, an 20. B is a column vector that looks like

1

2

3

C is the same as B.

More examples:

>> D = [1 2 3; 4 5 6; 7 8 9];

>> E = [1 2 3

4 5 6

7 8 9];

>> F = [1 2 ...

3; 4 5 6;

7 ...

8 9];

This creates the matrix D having 3 rows and 3 columns. It looks like this:

1 2 3

4 5 6

7 8 9

E and F are identical to D. The three dots used in defining F allow us to continue the list of values in a given row on the next line. The semi-colons separate rows. When the three dots are not used the return key also indicates the end of a row. It is important to remember that all rows of a matrix must have the same number of values. Similarly for the columns. It is easy to mistype and leave out a value. If you do that you will get an error message.

Reminder: If we leave the semi-colons off the ends of the commands when entering these definitions, the values of the matrices will be displayed.

Referencing Elements and Sub-matrices: In Matlab the rows and columns are numbered starting with 1 (instead of 0 as in Java). If A is a matrix, the expression A(i, j) is the element in row i column j of A. Notice that we use parentheses and a comma instead of the pair of square brackets that are used in Java. As in Java (and in mathematics), we always give the row index first and the column index second.

In Matlab we can also easily name a sub-matrix of a given matrix. For example, if A is a 6 by 7 matrix, the command

>> B = A(2:3, 2:6)

defines B to be a matrix with 2 rows and 5 columns. The values in B will be those Contained in rows 2 and 3, in columns 2 through 6 of A.

>> C = A(2:3, : )

defines C to be the matrix containing rows 2 and 3 of A. The use of ‘:’ without any numbers around it indicates that all columns should be included. Finally,

>> D = A( : , [3 4 7])

defines D to be the 6 by 3 matrix containing columns 3, 4, and 7 of matrix A.

Operations on Vectors and Matrices:

Scalar multiplication: If A is a matrix and x is any number, the product x*A is a matrix with the same shape as A in which every element is x times the corresponding element in A. That is, the entry in row i column j of the result equals x*A(i, j).

If two matrices, say A and B, have the same shape we can add them, subtract them, and do other element-by-element operations. The result is a matrix of the same shape. Notice carefully that the last three operations are written using a dot ( "." ) right before the operator symbol. This means that the operation is done element by element. These are not the usual matrix operations of multiplication, division, and exponentiation that some of you are familiar with. For those of you who know about matrices from mathematics, by leaving off the dot you can perform the normal matrix operations.

Symbol Operation

+ addition

- subtraction

.* element-by-element multiplication

./ element-by-element division

.^ element-by-element exponentiation

Example: If A = [1 2 3; 4 5 6], B = [20 30 40; 50 60 70] and C = [0 2 3; 1 3 2], then we get the following.

2*A = [2 4 6; 8 10 12]

A + B = [21 32 43; 54 65 76]

A .* B = [20 60 120; 200 300 420]

A .^ 2 = [1 4 9; 16 25 36]

A .^ C = [1 4 27; 4 125 36]

There are many more built-in operations and functions. See our Matlab syllabus for a few more, including the size and max functions. You can use the help command to learn more about them. Just type in help max, for example. (Don't forget our warning above about the usage of lower and upper case in the help command.)

Changing the Shape of an Array (For more information see Pratap p.47):

The symbol [ ] represents the null matrix. One use of this matrix is for deleting columns, rows, or sub-matrices of a matrix.

Example:

A(2:2, : ) = [ ] removes row 2 from A

So does the command A(2, : ) = [ ]

A(2:4, : ) = [ ] removes rows 2 through 4 from A.

 

We can build a new matrix by combining other matrices or parts of matrices.

Example: If A = [10 20 30; 40 50 60; 70 80 90] and v = [1; 2; 3], then the command

M = [A(1:1, : ); [1 5 9]; A(2:3, :)]

creates matrix M that looks like

 

10 20 30

1 5 9

40 50 60

70 80 90

Notice that M has the first row of A as its row 1. Its second row is the vector [1 5 9]. Its third and fourth rows are the same as rows 2 and 3 of A.

The command N = [ v A] creates the matrix

1 10 20 30

2 40 50 60

3 70 80 90

Some Extra Goodies: There are many useful built-in functions. Some of them are on page 48 of Pratap.

The function ones can be used to create a matrix of all ones.

A = ones(2, 3) creates a 2 by 3 array of 1’s.

Similarly, the function zeros is used to create an array of zeros, eye creates an identity matrix, and the function rand creates an array of random real numbers between 0 and 1.

The function linspace is used to produce a vector of numbers evenly spaced over a specific range. The command C = linspace(a, b, n) assigns C a vector containing n values evenly spaced between a and b.

For example, the command D = linspace (0, 10, 5) assigns D the vector [ 0 2.5 5 7.5 10 ]

The : notation also produces a vector of evenly spaced numbers. [a:b] produces a vector ranging from a to b by ones, while [a:c:b] produces a vector that ranges from a to b in steps of size c. For example:

>> [4:7]

[4 5 6 7]

>> [1:0.25:2]

[1 1.25 1.5 1.75 2]

The function sum(v) yields the sum of the elements of v if v is a vector (one row or column). If A is an m by n matrix with more than one row and column, then sum(A) yields a row vector having n columns. The value of each element in the vector is the sum of the elements in the corresponding column of A.

If A is a square matrix, diag(A) is the vector containing the major diagonal of A.

The transpose of a matrix A is the matrix formed by taking the rows of A and making them the columns of the new matrix. If the matrix is square this amounts to flipping the values over the major diagonal. The single quote symbol ' in Matlab produces the transpose.

Example: If A = [1 2 3] and B = A’ then B is the column vector

[1

2

3]

If A = [1 2 3

4 5 6

7 8 9]

and B = A’ then

B = [1 4 7

2 5 8

3 6 9]

A = A’ changes A to its transpose.