1. Introduction to MATLAB

Welcome to the MATLAB component of Math 20D!  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: 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. Plots & graphs Include all graphs generated in an exercise unless the problem specifically tells you which/how many to include. Full sentence response Each exercise contains a question. You should answer with at least one or two complete sentences.  Even if you're stuck, write down any reasoning or ideas you've had. 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.

If you are having trouble getting started, be sure to check out the Introductory Tutorial for Preparing Your MATLAB Homework (If the link doesn't open in your browser window, right click and save it to your harddrive).

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 Basic Operations

We can use MATLAB to do simple calculations with addition (+), subtraction (-), multiplication (*), division (/) and exponentiation (^).   (The asterisk for multiplication is Shift-8 and the caret for exponentiation is Shift-6.)

Example 1.1

Let's use MATLAB to calculate 1003/2 + (5*7 - 99)/2.  We enter this as

>> 100^(3/2) + (5*7 - 99)/2

and press the Return key.  MATLAB responds

ans =
968
Notice the use of parentheses!  MATLAB uses the usual order of operations, namely without any parentheses, ^ is applied first, then * and /, and finally +, - are applied.  If at all in doubt about how something will be evaluated, use parentheses.  Also note that the spaces between the numbers and operations are not strictly necessary, but they improve readability.

Remark 1.2  The most common source of errors is information incorrectly entered into MATLAB.  Make sure you familiarize yourself with the correct order of operations for each piece of data you enter into MATLAB, and enter it into the program using parentheses to designate the correct order of operations.  This will save you a lot of hassle down the road.

§1.2 Elementary Functions in MATLAB

Example 1.2

This example introduces some trigonometric and logarithmic functions and the use of letters (or strings of letters) to refer to numbers.

>> a = sin(pi/12)
a =
0.2588

>> b = cos(pi/12)
b =
0.9659

>> result = a^2 + b^2
result =
1

Notice pi is pre-assigned the value of 3.14159....  MATLAB knows pi to great accuracy.  To see this we can use the vpa command:

>> vpa(pi, 800)

(This might take a few seconds to execute.)  This command tells MATLAB to display the first argument (in this case pi) to the indicated number of digits.

Another letter that is often used in mathematics is e, the base of the natural logarithm. MATLAB does not initially know e, but MATLAB has the exp function where exp(t) = et.  Hence, if we want e we can type

>> e = exp(1)

In MATLAB log(x) refers not to log10(x), but to loge(x) which you've probably seen written ln(x).
 Exercise 1.1  Recall the elementary formula: logb(x)=ln(x)/ln(b).Use MATLAB and this formula to calculate log8(20). Include the input and output in your word document.

§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

>> doc

NOTE: MATLAB occasionally changes their commands. If you are using an old version of MATLAB (before 2013) the command "helpbrowser" may work instead.

In any case, this command 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 What You Need To Know About MATLAB page.

Some commands in MATLAB generate excessive output.  For example try typing the following

>> m = -3:0.4:12
 Exercise 1.2  By examining the output, explain what the previous command did.  (You need not include the output in your Word document.) How do you think MATLAB would respond if you type m(26)? Try it.

On the other hand if we enter:  (notice the semi-colon at the end!)

>> n = 4:2:200;

there is no output.  MATLAB has carried out the command but has suppressed the output.  If, afterward, we decide we do wish to see the output, we can do so by typing

>> n

In the course of these labs, we will usually include the semi-colon in the example code if the output is excessively long or if the output is routine (for example, if we are just assigning a value to a constant and already know what the output is going to be).  Keep in mind, however, that aside from the two cases just mentioned, you need to include the exercise-related outputs.

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.
 Exercise 1.3  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 use the left and right arrow keys to correct the error(s). Include the wrong command, the error message, and your fix in your homework.  (Hint: Good things to check are multiplication and parentheses.)

§1.4 Graphing Functions

Example 1.3

Let's compare two methods of graphing functions: ezplot vs. fplot.  (Later on in the lab we'll see another command, plot, useful for graphing sequences.)  Let's enter the function f(x) = cos(x)/(1 - x).  This is done with the following command:

>> f = inline('cos(x)/(1-x)')

Now we want to graph f(x) on the interval [-10, 10].  Using fplot this can be accomplished with

>> fplot(f,  [-10, 10])
>> title('The result of fplot')

Now try the same graph with ezplot:

>> figure
>> ezplot(f, [-10, 10])

(The command figure brings up a new graphics window.  MATLAB will draw on whatever graphics window was most recently in the front.  Hence, if you omit figure, the second graph will overwrite the first.  Or, perhaps even more confusingly, if you type figure, then bring the first plot to the front, and then enter the ezplot command, it will unfortunately still overwrite your first graph!)

Here are the resulting graphs:

Clearly the two routines chose different values to bound the y coordinate!  As a result, the fplot-figure is misleading since the function doesn't actually have a positive "spike" at x = 1, but rather an asymptote that approaches infinity in two different directions, as we can see in the ezplot figure.  Let's change the y-bounds to be -1 to 1 in the first figure (the one produced by fplot).  Do this by bringing that window to the front and choosing the menu option Edit -> Axes Properties....  After a short delay, you will get the following window:

The first thing to do is to click on the thumbnail-tab "Y Axis".  Next uncheck the Auto box.  This will turn the "Y Limits" boxes white, allowing you to edit their contents.  Replace the bounds with with -1 and 1, pressing ENTER after entering the values.  The  result after rescaling is:

Notice how "rough" the graph still appears to the right of x = 1.  This is probably due to it being originally graphed on such an extreme scale on the y-axis.  (If we had known that we wanted certain bounds on y beforehand we could have entered e.g. fplot(f, [-10, 10, -1, 1]).)  Because this function has a vertical asymptote at x = 1, no matter what we do fplot errantly draws a vertical line there.
 Exercise 1.4  Graph the function g(x) = sin(x)/x on the interval [-10, 10] with fplot. Include the MATLAB code you used.  Then paste the graph into your Word document.  To copy the graph bring its window to the front and choose the menu option Edit -> Copy Figure.

§1.5 M-Files and For Loops in MATLAB

If you haven't used MATLAB extensively before, at this point MATLAB may seem to be simply be just a powerful calculator.  However, MATLAB has many features which will allow us to do easily perform computations which would require extensive work (or be impossible) with a calculator.  In this section we will look at two such tools: for loops and M-Files.

For loops. Often times we wish to perform a task repeatedly.  MATLAB (along with most programming languages, for that matter) has a built in tool known as a for loop.  Suppose, for instance, we wanted
to print out the squares of the integers from 1 to 4.  One option would be to type each square in individually.  However, a better way to do a repetative task like this is to use a for loop. To do this, type the following into MATLAB at the command prompt:

>> for i = 1:4
i^2
end

ans =

1

ans =

4

ans =

9

ans =

16

After pressing enter, MATLAB prints out the square of each integer from 1 to 4.  What is going on here?  The line for i=1:4 tells MATLAB to set the variable i equal to 1 initially.  The next line, i^2, prints out i^2 = 1^2 = 1.  We have finished the body of our loop, so MATLAB increases i to 2, starts from the top again, and prints i^2 = 2^2 = 4.  The for loop continues until i = 10.  One thing to note is that the loop, like all MATLAB commands, will supress output if we add a semi-colon after the line i^2.  Of course, the purpose of this loop is to print out those numbers so we omit the semi-colon here.

We will return to for loops shortly, but for now let us look at another powerful tool in MATLAB: the M-File.

M-files.  As some problems get more complicated, or simply take more commands to run, the command prompt window in MATLAB can start to become cumbersome.  A better approach in situations like this is to create and use an M-File.  An M-File is a simple text file that contains MATLAB commands which you can call from the regular MATLAB command window.  M-Files can either be functions or chains of commands called scripts; we will mainly use them for defining our own functions.

To create a new M-File, go to File -> New -> Blank M-File.  (Or, in some versions, New -> Script.  or simply New Script. ) A text editor will appear, allowing you to enter the contents of the M-File and save it.  Open a new M-File now, and enter the following text into the editor:

1    function printSquares;
2    for i=1:4
3        i^2
4    end

Note: Do not enter the numbers 1, 2, etc.; these will be on the side of the editor already.  The first line of the M-file defines the name of the function, printSquares.  The remainder of the file is the same for loop as above.

Now save the M-File as "printSquares.m".  This name will probably appear in the save window for you.  The file should be saved in a directory where MATLAB can access it.  If you are working on an ACS machine, use the "work" folder (this is the default).  If you are not working on an ACS machine, make sure you are saving the file into MATLAB's working directory on your machine. (Your working directory is indicated at the top of the main MATLAB window; you can change it if you need MATLAB to be able to see an m-file in a different location).

Once we have done this, in the main MATLAB command window, type:

>> printSquares

As you can see, this command does the same thing as our for loop we entered directly at the command prompt.

Why is this useful?  Well for one thing, we don't need to retype the code for the loop everytime we want to run it.  We should be very thankful for this, since MATLAB programs can be quite long!  For more complicated code, there are other reasons as well.  Let's look at expanding the M-File above to make it more useful.

The M-File above prints the first four squares.  But what if we wanted to print the first 10?  Well, one option would be to change the number in our M-File, save it, and then run it again at the prompt.  However, there is an even better way to do it: we allow the call to the M-File to accept as input the number of squares to print.  Go back to your M-File and change it so that it now reads:

1    function printSquares(numberOfSquares);
2    for i=1:numberOfSquares
3        i^2
4    end

Be sure to save it again as "printSquares.m".  Now run it at the command window by typing:

>> printSquares(10)

Try entering this command with values other than ten.  As you can see, our code now prints out the first n squares, where n is the value you give as the argument for the printSquares function.

While MATLAB has a lot of built in commands, it can't possibly have everything we would want built into it.  Thus M-Files are extremely important as they allow us to create our own MATLAB commands.  Note that M-Files aren't limited to for loops or using only one input either.  The possibilities are endless.

We will look at one more example of the use of M-Files and for loops, but before we do let's try having you create your own:

 Exercise 1.5 (a)  Recall that a geometric sequence is a sequence of the form  a, ar, ar2, ar3, ...  At the MATLAB command prompt (not in an M-File), create a for-loop which prints the first 7 terms of this sequence when r = 1/3, a = 1.   Include the output in your Word document. (b)  Create a new M-File "geomSeq" with the loop above (be sure to test it to make sure it works!).  Include the code for you M-File in your Word document. (c)  Modify your M-File so that it accepts the value of r as an argument.  Use this to find the first 7 terms of the geometric sequence when r = 1/4.  Include the output and the command you used in your Word document.

Using for loops to compute series.  Recall that a geometric series is a series of the form a + ax + ax2 + ax3 + ...  Geometric series appear in many applications, including compiling interest on bank accounts.  For example, if you deposit \$100 each year into a bank account, and the account earns interest at a rate of 3% each year, then after four years (that is, before making your 5th deposit), the balance of your bank account will be 100(1.03) + 100(1.03)2 + 100(1.03)3 + 100(1.03)4 dollars. (Take a moment to make sure you agree.)  Here is the M-file we type in to do this:

1    function sum = bal(yearlyDeposit,interestRate,years)
2    sum = 0;
3    for i=1:years
4        sum = sum + yearlyDeposit*(1+interestRate)^i;
5    end

Once we save this file as "bal.m" in our working directory, we will have a new command in MATLAB, bal, which takes three inputs and returns the proper balance.  The command

>> bal(100, 0.03, 4)

ans =

430.9136

tells us that in our example, the balance of the account would be \$430.91 after four years.  Note the file name bal.m corresponds to the function name bal; this is no accident. MATLAB requires this.

There are a few differences between this loop and the one ones above.  The first major difference is that the first line now includes a variable, sum, followed by an equals sign, between the word function and the name of the M-File.  This is telling the M-File to return the value of sum once the function has finished running.  We also included semi-colons to supress output of the loop, since now we are only interested in the final value and not the intermediate values.  Removing semi-colons can often be useful to see exactly what the function is doing, however;  this is especially useful for finding bugs in a program.

The other thing to notice is that we have used a common programming trick for computing a series.  In the first line of the function body we define the variable sum, which we set to zero initially.  After each run of the loop, we compute the next term in the series and add that to sum.  Thus each time our loop runs, it adds the new value to sum, and we keep a running total.  This is a much more common use of for loops than printing out values.  Let's have you give it a try with the following exercise:

 Exercise 1.6 (a)  Consider the series 1 + 1/r + 1/r2 + 1/r3 + ... + 1/rn. Implement a calculation for this series in a new M-file, calling the function "mysum".  The function should take two inputs, r and n. (b)  Use the new command, mysum, to calculate the value when r = 3 and n = 12.

§1.6 The dsolve command

dsolve is a helpful tool in MATLAB which can produce symbolic solutions to basic differential equations. It is based on rather complicated algorithms for recognizing certain types of  differential equations and solving them.

Consider the differential equation  dy/dt = k*y

You probably recognized this as a linear or separable equation. The solution is given by

 y = A ekt

where A is a constant, which is equal to y(0).

Let us see how dsolve solves this equation.

Enter the following command

>> dsolve('Dy=k*y')

The output is just what we expected (with C1 being the constant we called A). We can also add an initial condition to the equation, as follows:

>> dsolve('Dy=k*y', 'y(0)=5')

Remark 1.3  The default independent variable in dsolve is t. Thus, if we want to have y as a function of, say, x, then we must specify this as follows:

>> dsolve('Dy=k*y', 'x')

Even if we enter a function of x into dsolve, it will not know this unless it is specified. Thus

>> dsolve('Dy=2*x')

will not give us y=x^2+C as you might expect,  but instead we get 2*x*t+C1, as dsolve considers x to be a constant.

 Exercise 1.7 (a)  Consider the differential equation  dy/dt = sin(t). Solve this equation by hand, without using MATLAB (Hint: just integrate both sides). (b)  Now use dsolve to solve the differential equation. (c)  Using dsolve solve the equation with the initial condition y(0)=3.

While dsolve may be useful at times, it has its limitations. For one, it does not solve any equation. Also, the solution may be given in a form that is not useful to us.

 Exercise 1.8  Make up a differential equation that dsolve cannot solve. You should receive a warning message saying "explicit solution could not be found". (Hint: you may need to experiment a little until you find such an equation. Try putting complicated functions of y and t on the right-hand side. You may find the up-arrow key particularly useful here).  Copy and paste to your word document, just the input and output for the equation you find that can't be solved, not for all of your experimentation.

For more information on dsolve (as with any MATLAB command) you can type in

>> help dsolve

§1.7 Differentiation in MATLAB

MATLAB can compute derivatives using the diff command. But first we must declare what variables we are going to be using. Do this by the syms command. (Note: This procedure is different in old versions of MATLAB.)

>> syms x y

To take the derivative of, say sin(x), we can now type:

>> diff(sin(x))
ans =
cos(x)

MATLAB also alsos us to differentiate functions of more than one variable.  Let us use MATLAB to differentiate sin(x + 3y):

>> diff(sin(x + 3*y))
ans =
cos(x + 3*y)

Note that MATLAB by default takes the derivative with respect to x.  If we wanted to take the derivative with respect to y, we would type

>> diff(sin(x + 3*y), y)

 Exercise 1.9 Compute the derivative of ln(sin(s)+cos(t)) with respect to t and with respect to s.  Include the input and output in your word document.

§1.8 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.

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

If you are looking to get help with more general math topics, Wikipedia is an excellent resource.

§1.9 Feedback

Introduction to MATLAB
We're almost done, but before we finish we'd like to get some (optional) feedback from you so that we can improve this lab.  If you have any comments, write them (by hand if you like) on a separate page at the end of your assignment, so that we can tear it off before we give back your assignment.

 Feedback (Optional) Do you have any suggestions to help improve this lab?  This includes errors or potential errors, typos, unclear statements or questions, or anything else that comes to mind.  The more specific you can be, the easier it will be for us to improve the lab.

§1.10 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.