ICS 6N - Winter 2017
Lab 1: Introduction to MATLAB


What to hand in.

This lab will introduce you to some of the basic features of MATLAB. You should do the exercises below. As you do each one, copy the relevant input and output from MATLAB and paste it into a Word document. You need only include commands that worked. You will electronically submit your Word document in EEE's dropbox on the day that the lab is due. Make sure and include your name, student ID and which discussion section you are signed up for.

You should save your file temporarily on the machine in the lab. You should delete the file from the lab computer before your logout, but don't forget to save a more permanent copy, either by emailing it to yourself or storing it somewhere in the cloud.

Be warned that the future labs will be longer than this lab! Don't wait until the last minute to start.

The lab assignments will contain descriptions of commands and responses in MATLAB. Typically, the text that is input by the user is in red and the part that is printed by MATLAB is in black.

About MATLAB

Linear algebra is used in every branch of mathematics and is thus a crucial part of it. Linear algebra also has applications in practically every field of natural and social sciences. Physics, chemistry, biology, computer science, economics, and sociology have all benefited from the advent of linear algebra. In the lab sections this quarter you will see a few applications of linear algebra to some of these areas.

Problems that arise in these fields involve raw data, so professionals in these fields have come to depend on computers as an essential tool. Computer programs such as MATLAB help in performing tedious calculations so that you can spend less time crunching numbers. It turns out that MATLAB is especially well suited for working with matrices and performing various algorithmic routines that come up in linear algebra. In this lab we will start to get acquainted with MATLAB and learn how it handles matrices.

Variables in Matlab

People like to think of MATLAB as a very powerful calculator you can use on your computer. For our purpose, that is not far from the mark.

To define variables, simply type in the variable you wish to define, then an equal sign, and finally the value you wish to assign to that variable. So, if we want to assign the value of 5 to the variable x, we type

>>   x=5

x =
    5

Unless we later redefine x, every time we type "x" MATLAB will replace it with 5 when doing a calculation. For example, we can define the following variables by their place in the alphabet:

>>   l=12; i=9; n=14; e=5; a=1; r=18; g=7; b=2;

We have just assigned specific values to the given letters. (Note: the semicolons in this command suppress the output. If they were not there, once you hit return MATLAB would list the eight variables and their new values.) It is also possible to assign values to more than just single letters using MATLAB. It is sometimes easier to define something with a specific name rather than a single letter. For example, we can define

>>   UCIrvine = 92697

UCIrvine =
    92697

92697 is the zip code of UCI. Notice that there are no spaces in variable names. (We cannot define a variable called "UC Irvine".) Also, when defining something, MATLAB is case-sensitive so if we accidentally type "laytext" and hit return, we will get an error message as seen here.

>>   ucrivine

??? Undefined function or variable 'ucrivine'.

Using the variables we just defined, we can do some calculations and save them as specific names.

>>   linearalgebra = l+i+n+e+a+r+a+l+g+e+b+r+a

linearalgebra =
    105

>>   angle = a+n+g+l+e

angle =
    39
Exercise 1.1 Define the letters of your first and last name to be the number corresponding to their place in the alphabet. Then set your name, without any spaces, equal to the sum of the letters.

Hints and Tips

MATLAB has some useful features that are worth learning at this point.

If you ever get stuck or need more info, an excellent way to get help in MATLAB is by entering

>>   helpbrowser

This will allow you to view the syntax of various commands by reading their help files and to search for keywords.

Our final tip is to become very familiar with the use of the up-arrow key. Indeed at this point bring up the main MATLAB window and try pushing the up-arrow key on the keyboard once. Then push it a few more times. Notice that this is bringing your previously-entered commands back onto the command-line. You can also use the left and right arrow keys to position the cursor in a command in order to edit it. This is a great way to correct a command that had an error in it.

Exerxise 1.2 Suppose you want to calculate:
Enter the command:

>>   z = 25-(100-7exp(5+cos(pi/3))
You will get an error message. Use the up-arrow to bring this line back and then correct the error(s). (Hint: Good things to check are multiplication and parentheses.)

Matrices in MATLAB

The first thing to learn when dealing with matrices is how to construct a matrix (or vector) using MATLAB.

To define a matrix using MATLAB, we use the square brackets "[ ]". "[" tells MATLAB we are starting to create a matrix and "]" tells MATLAB that we have finished with our construction. The entries of the matrix should be entered in rows from left to right. To separate entries we can either hit the space bar or insert a comma ",". Once we finish with a given row and want to move to the next, we can either press the return key or use a semicolon ";". (This is not the same as using the semicolon to suppress output.)

So, to construct the following matrix

here are two possible ways to go about it:

>>   A=[2 1;4 3]

>>   A=[2,1 (Return key)

4, 3]

Both will yield the desired matrix:

A =

    2    1
    4    3
Exerxise 1.3 Input the following matrix into MATLAB:

Matrix operations and manipulations

Sometimes we need to get at certain parts of a matrix only, maybe just a certain row or even a single entry. This is done with regular parentheses, "(" and ")". For example, to see the (1,2) entry of the matrix A above (i.e. the entry in the first row and second column), we use the command

>>   A(1,2)

We also can use the colon ":" to mean 'all', as in the command

>>   A(2,:)

which will give us the entire second row of the matrix A. The colon can also be used to represent a range of rows or columns: the command

>>   Fibonacci(2:4,1)

will give us the entries of Fibonacci from the second through fourth rows in the first column.

Exerxise 1.4 Using the commands introduced above, construct a new matrix (call it whatever you'd like) from Fibonacci that consists of the last two rows and the two middle columns of Fibonacci. (So it will be a 2x2 matrix.) Be sure to include the command you used and the result output in your Word document.

A note about matrix operations: two matrices A and B can be added together or subtracted from one another ONLY if they are the same size. (If they are not the same size, MATLAB will produce an error.)

Random matrices

From time to time, we will be working with random matrices in this class. However, when you are asked to create a random matrix, this does not mean you should just create a matrix using numbers that pop up in your head. Instead, we will let MATLAB do the "thinking".

To create random matrices, we use the rand() command.

Notice the parentheses after the command. When using a command that requires some type of input, that input must be put in parentheses. We cannot use square brackets here because when MATLAB sees square brackets, it assumes we are talking about a matrix.

Typing

>>   rand(n)

and hitting return tells MATLAB to create a random n x n matrix whose entries are decimal values between 0 and 1.

Now if we type

>>   RMatrix1=rand(2)

we will see the following:

RMatrix1=

    0.9501    0.6068
    0.2311    0.4860
Exerxise 1.5 Create 2 random 4 x 4 matrices A and B and calculate the following values. (You should store each of them in a variable with some name of your choosing.) In theory, do you expect the following matrices to be equal? Are they?

A + B

B + A

MATLAB's built-in help command

While these labs are written to be as self-contained as possible, you may find that you've forgotten what a MATLAB command does or wonder what else MATLAB can do. Fortunately, MATLAB has an extensive built in help system. For instance, suppose we want to know what applying the cumprod command to a vector does. Type

>>   help cumprod

to bring up the help description.

There are three parts of note for this decription. The first part gives a brief description of the function and tells us how of the possible ways we can use the function. Note that there are several different options, depending on what is passed to the function. The second part, 'Examples', gives us examples of how to use the function. Often, reading through the examples is the best way to determine how a function works. Finally, the third part gives related commands.

For instance, here the first line of the description is "For vectors, CUMPROD(X) is a vector containing the cumulative product of the elements of X" - that is, it multiplies the elements one at a time and stores the cumulative results. For instance,

>>   cumprod([2 3 4])

ans =
   2     6    24

Looking at the help description, you can see there are many possible uses for the cumproduct command. In general, MATLAB commands have a lot of flexability.

Exerxise 1.6 How do you find sin-1(1) using MATLAB? (Hint: Start by looking at help sin)


Acknowledgement: This lab is based upon a series of labs developed by faculty and graduate students at UCSD (http://www.math.ucsd.edu/~math20f/Fall/MatlabIndex.html)