1. Introduction to MATLAB

   

Welcome to the MATLAB component of Math 20F!  If you are reading this, you are probably already logged into a PC. . . if not, click here for instructions on that.  The next thing to do is run MATLAB and Microsoft Word.  (You can find instructions for that here.)

    Be sure to include your name, section (e.g. B03), and TA's name at the top of your Word document.  As you complete a lab assignment you should enter all the commands listed and work through the Examples.  But in your Word document you only need to include your responses to the Exercises.  These responses should consist of what exercise you are answering clearly labeled and then whatever combination of the following four items is applicable:
 

Icon: Item: Comments:
Include input and output. Commands entered in MATLAB & resulting output  You should copy relevant input and output from MATLAB and paste it into your Word document (see Remark 1.1 below).  You need only include commands that worked.
Include plots and graphs. Plots & graphs  Include all graphs generated in an exercise unless the problem specifically tells you which/how many to include.
Include full-sentence response. Full sentence response Exercise contains a question that you need to use at least one or two complete sentences to answer.  Even if you're stuck, write down any reasoning or ideas you've had.
Do work by hand. Requires work by hand  Do scratch work by hand.  Leave space in your Word document and write your scratch work directly on the assignment to turn in.

Remark 1.1  After selecting text with the cursor, there are in general three ways to copy it: (1) choosing Edit -> Copy from the menu bar, (2) clicking the right mouse button and then choosing Copy from the resulting popup menu, or (3) pressing Ctrl-C.  We only point this out because the latter options are usually faster and more convenient than the first, but less well known.  Likewise, pasting can be accomplished with (1) choosing Edit -> Paste, (2) right-clicking and choosing Paste, or (3) pressing Ctrl-V.  Copying plots and figures is slightly different from copying text, as we will point out later in this lab.

    You may wish to save your work as you go (in case of a computer crash, etc.).  Click here for tips on that.  

    Before we begin, one important note: you are encouraged to talk to your fellow students as you work through a lab.  If you're stuck, try introducing yourself to your neighbor.  Feel free to discuss responses to difficult exercises.  However, in the end, you must submit your own work written in your own words! 

Identical responses will be penalized at the grader's discretion!!!

    Let's get started.  After you've run MATLAB, it should be sitting there with a prompt:

>>

    When working though examples or exercises, do not type the prompt (>>), simply the commands that follow it (which are listed in red).  When you are given commands in either examples or exercises, you may want to consider copying the text from the webpage and pasting it into MATLAB next to the prompt rather than trying to type it into MATLAB yourself, which tends to cause inadvertent errors.

§1.1 Introduction

    Linear algebra is used in every branch of mathematics and is thus a crucial part of it.  But if you think that you'd sooner walk on burning coals while being whipped from behind by a five thousand pound gorilla than do something stupid and major in math, be aware that linear algebra 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, and working with it by hand, without the aid of computers, may be just as crazy as being whipped by a five thousand pound gorilla.  Computer programs such as MATLAB help in performing tedious calculations so that you can spend less time crunching numbers and more time working on the design of your time machine.  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. 

§1.2 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

>> LayText=492

LayText =

   492

since our textbook has 492 pages.  Notice that there are no spaces in variable names.  (We cannot define a variable called "Lay Text".)  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.

>> laytext

??? Undefined function or variable 'laytext'.

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

 

>> ringingbell = r+i+n+g+i+n+g+b+e+l+l

ringingbell =

    109
 

>> largebill = l+a+r+g+e+b+i+l+l

largebill =

    78

Include input and output. 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.

§1.3 Hints and Tips

    MATLAB has some time- and headache-saving 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.  The other thing to check before asking your TA is the Math 20F MATLAB FAQ.

    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.  This is a great way to correct a command that had an error in it.  

Include input and output. Exercise 1.2  Suppose we want to evaluate
 

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.)

 

§1.4 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 

Include input and output. Exercise 1.3  Input the following matrix into MATLAB:

§1.5 Matrix Operations and Manipulation

    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.

Include input and output. Exercise 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.)  Also, two matrices can only be multiplied if their dimensions allow it; for example, if A is a 2x3 matrix and B is a 3x4 matrix, then A*B will work in MATLAB, but B*A will produce an error.

§1.6 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

Include input and output. Include full-sentence response. Exercise 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, which of the following matrices do you expect to be equal?  Which ones actually are equal?

A*B
B*A
A + B
B + A

§1.7 Conclusion: Printing and Submitting Labs

    That's about it for Lab 1!  At this point your Word document should be ready to print out and submit.  Check with your TA as to when and where labs are to be turned in; often they are due in discussion section.

    In order to print your lab on a laser printer in CLICS, the basement of AP&M, or other labs on campus, you will need to have an ACS laser printer account.  This may take a few days to set up, so do it ASAP.  For details on getting said account and also instructions on printing, visit the page http://www-acs.ucsd.edu/print/.  In CLICS the nearest laser printer is laser64 which is in the northeast corner of the upper floor.  Another choice is laser63, located in the printer room near the bottom of the stairwell.  If you fail to specify a printer or don't have a printer account, there is no error generated when you try to print--but no printout will appear on any printer.

    You may prefer to email your lab to yourself as an attachment, and then print it out on your home printer.  It is also possible to use a disk to transfer your file.

    After you have printed or at least saved your lab document, remember to log-out of your PC.  You do this by choosing START -> Log Off.

    A few final comments and warnings:

(1) The labs are designed to be completed on specific ACS lab PC's.  Use home versions of MATLAB or versions on ACS Macintoshes at your own risk.
(2) TAs are available for help during lab time, not via e-mail the night before the assignment is due.
(3) No emailing labs to TAs.
(4) Your TAs may become seized with paroxysms of despair if you fail to staple your lab.  (Not a pretty sight, what with the crying and the gnashing of teeth.  Plus, they might take points off.)  However, do not staple your lab to your regular homework, or the same lunacy will ensue.
(5) It's MATLAB, not "Mathlab"!


Last Modified:

07/27/2008