Introduction to MATLAB

Welcome to the MATLAB component of Math 18! If you are reading this, you have probably successfully logged in to a PC; if not, go here for instruction on how to do that. You now need to run both MATLAB and a word processor—we'll assume you're using Microsoft Word. Instructions for that are here.

In the header of your Word document, be sure to include your name, section number, & TA's name.

As you complete a lab assignment, you should read along, enter all the commands listed in the tutorials, and work through the Examples. However, in your Word document, you need only include your responses to the Exercises. Each response should clearly indicate which exercise it answers. The exercises will require different kinds of responses; the type of answer we are looking for will be marked by some combination of the icons described below.

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. 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 Answer questions with at least one or two complete sentences. Even if you're stuck, write down any reasoning or ideas you've had.
Do work manually. Requires manual work Do scratch work without using MATLAB. Record this work in your Word document, either by typing it or scanning it.

It is good practice to save your work as you go, in case of computer crash, power outage, etc.

We encourage you to talk to your fellow students while you work through the assignments. 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!

Finally, there is one last important thing you should be aware of: the MATLAB quiz. It will take place in Week 10. Due to the COVID-19 pandemic, we are deciding on the best way to offer the quizzes. Information about the quiz is available on the main page. (This exercise will not be graded)

Include full-sentence response.
  1. What is the date of your MATLAB quiz? What day of the week is that?

First Steps

Our goal in this first lab is to get acquainted with MATLAB and learn how it handles matrices. After you've run MATLAB, it should be sitting there with a prompt:


When working through examples or exercises, you should omit the prompt (>>) and just type the commands that follow it (which are displayed like this). When you are given commands in either examples or exercises, instead of typing them into MATLAB yourself, you may want to consider copying the text from the webpage and pasting it into MATLAB next to the prompt. This can help avoid inadvertent errors.

Basic Operations

We can use MATLAB to do simple addition (+), subtraction (-), multiplication (*), division (/), and exponentiation (^).

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

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

and press the Return key. MATLAB responds

ans =

Notice the use of parentheses! MATLAB respects the usual order of operations. Namely, if no parentheses are used, then exponentiation is done first, then multiplication & division (from left to right), and finally addition & subtraction. If you're ever in doubt about how something will be evaluated, use parentheses.

Strictly speaking, we don't have to put spaces between the numbers and the symbols, but they help make our code more readable.

By far the most common source of errors in this course will be data entry errors—that is, errors made by typing commands or data incorrectly. Make sure you understand how MATLAB works with the order of operations, and use parentheses as needed to designate the correct order of operations. This will save you a lot of trouble down the road.

Naming Variables

MATLAB allows us to use letters (or more generally, a letter followed by any string of letters, numbers, and underscores) to assign names to variables. This allows us to easily reuse past results.

Suppose we'd like to assign the value 5 to the variable x. In MATLAB, we type

>> x = 5

x =

Unless we later redefine x, MATLAB will replace x with 5 every time x appears in a calculation. Let's define a few more variables by their place in the alphabet:

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

Notice that when you run this code, you don't get any output. The semicolons here after each command tell MATLAB to suppress output.

You can also assign names that are longer than a single letter, like so:

>> DaysPerYear = 365

DaysPerYear =

Note that spaces are not allowed in variable names, so you can't define a variable called Days Per Year. You should also be aware that MATLAB is case-sensitive. If we accidentally type daysperyear, we'll get an error message:

>> daysperyear

??? Undefined function or variable 'daysperyear'.

Using the variables we just defined, we can do some calculations and assign names to the results.

>> leapyear = DaysPerYear + 1

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

linearalgebra =

Include input and output.

Define each letter of your first and last names to be the number corresponding to its place in the alphabet. Then set your name, without any spaces, equal to the sum of the letters.

Hints & Tips

MATLAB has a number of time-saving features that are worth learning now.

The semicolon. We've mentioned this already, but it's important enough to highlight again. You'll notice while working with MATLAB that some commands will generate extremely long output. For example, try typing the following:

>> m = -3:0.4:12

On the other hand, if we enter the following: (notice the semicolon!)

>> n = 4:2:200;

there is no output. MATLAB has carried out the command, but the semicolon tells it not to print the result. If at some point later on, we'd like to see the output, we can do so by typing

>> n

For this course, we will usually include the semicolon in the example code if the output is excessively long or if the output is routine (for example, if we are just assigning a name to a constant and we already know what the output is going to be). Except in these two cases, you need to include any outputs related to the exercises.

Shift+Enter. We haven't had any need to do this so far, but it will be useful later to be able to run multiple inputs all at once, without typing out and running each line in sequence. You can jump to a new line without running your code by typing Shift+Return or Shift+Enter.

The up-arrow key. 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.

Include input and output.

Suppose we want to evaluate the expression

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: Multiplication and parentheses are good things to check.]

Computer Algebra

One of the most useful features of MATLAB is its ability to do what is known as symbolic manipulation, which includes things like solving an equation for a particular variable. But first, we must declare what variables we are going to be using. Do this by the syms command:

>> syms x y

Now type

>> a = (x + y)^3
a =
   (x + y)^3

Note that you will receive an error message if you failed to first input syms x y as above. If we wanted to expand the cubic here, we could now type

>> expand(a)
ans =
   x^3 + 3*x^2*y + 3*x*y^2 + y^3

Conversely, you could start with this last expression and factor it:

>> factor(x^3 + 3*x^2*y + 3*x*y^2 + y^3)
ans =
   (x + y)^3

MATLAB also does differentiation and integration with diff and int. To take the derivative of, say, sin(x), type in:

>> diff(sin(x))
ans =

MATLAB also allows 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 takes the derivative with respect to x and not y; by default, it will choose whichever symbol is closest to the letter X in the alphabet. If we wanted to take the derivative with respect to y instead, we would type

>> diff(sin(x+3*y),y)
Include input and output.

Compute the derivative of log(cos(t)-3*s) with respect to t. Next, differentiate the same function with respect to s instead. Include the input and output in your Word document.

We will not be using these particular tools for the rest of the Math 18 MATLAB course, but they might be useful to you in other settings.

MATLAB's Built-in Help

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 you may wonder what else MATLAB can do. Fortunately, MATLAB has an extensive built-in help system. If you ever get stuck or need more info, one excellent way to get help in MATLAB is by entering

>> doc

This command will take you to MATLAB's searchable documentation, where you can learn how to use all the built-in MATLAB commands by reading their help files. This is a particularly good resource when you know what you want to do but don't know which commands to use. For example, if you want to integrate something but don't know how, a search for "integral" will suggest both integral and int.

If you already know which command you want, but you've forgotten how exactly it works, one quick way to access its documentation is to enter help followed by the name of your command. This will usually give you a brief description of the command, some examples, and a list of related commands.

Include full-sentence response. Include input and output.

Compute arcsin(1) using MATLAB. Include the outputs in MATLAB. [Hint: Start by looking at help sin, or perhaps doc arcsine.]

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

Matrices in MATLAB

If we want to do any linear algebra with MATLAB, we first have to learn how to construct a matrix (or vector) in the program. To do so, we use the square brackets, [ and ]. The left bracket [ tells MATLAB that we are starting a matrix, and the right bracket ] tells MATLAB that we are finished. The entries of the matrix are entered in rows from left to right. To separate the entries in a row, we can use either a space or a comma (,). To mark the end of a row, use a semicolon (;). (This is not the same as using the semicolon to suppress output.)

So, to construct the following matrix in MATLAB,

we have two possibilities:

>> A = [2 1; 4 3]
>> A = [2,1; 4,3]

Both will yield the desired matrix:

A =
   2   1
   4   3
Include input and output.

Input the following matrix into MATLAB:

Matrix Operations and Manipulation

We often wish to take a matrix that we have defined and have MATLAB tell us information about it. For example, maybe we want to know what number is in the third row and fourth column, or maybe we want to view the whole fifth row. These tasks are done with regular parentheses, ( and ).

To see the (1, 2) entry of the matrix A above (that is, the entry in the first row and second column), we use the command

>> A(1,2)

We can also 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.

Using the commands introduced above, construct a new matrix with whatever name you like from Fibonacci that consists of the elements in the last two rows and the middle two columns of Fibonacci. (The result should therefore be a 2×2 matrix.) Be sure to include the command you used and the resultant output in your Word document.

Two matrices A and B can be added together or subtracted from each other only if they are the same size. If they are not, MATLAB will respond with an error.

Random Matrices

From time to time, you will want to work with matrices whose elements are random. However, when you need a random matrix, it's not good enough to just make a matrix with numbers that pop up in your head—humans are notoriously bad at generating randomness. In fact it's also difficult for computers to create truly random numbers, but MATLAB includes algorithms that generate "pseudorandom" numbers. These are close enough to being truly random for many purposes.

We will generate random matrices with the rand() command. Notice the parentheses here; when a command requires some type of input (an argument), that argument must be put in parentheses. In this case, the argument for rand() indicates the size of the matrix that MATLAB should create. Hence, typing

>> rand(n)

will tell MATLAB to create a random n×n matrix whose entries are decimal values between 0 and 1. If we type

>> RMatrix1 = rand(2)

we will see something like the following (but with different numbers):

RMatrix1 =
   0.9501   0.6068
   0.2311   0.4860
Include full-sentence response. Include input and output.

Create two random 4×4 matrices named A and B. Do you expect A + B and B + A to be equal? Compute those two sums using MATLAB. Are they in fact the same?

Conclusion: Submitting Labs

That's about it for Lab 1! At this point, your Word document should be ready to submit. In order to submit your document, you need to be enrolled in this course at Gradescope. This should happen automatically during the first week. However, if at the end of week 1 you do not yet have access to your class's MATLAB Gradescope page, you should contact your regular discussion section TA and explain the situation. Give them your name, UCSD email address, and PID, and they'll be able to add you to the course manually.

Please note that when submitting HWs on gradescope, you're required to assign correct pages to your problems. If your solution to a problem consists of a few pages, you should include all of them. This will greatly help the graders find your work. Otherwise they have to scroll up and down to look for your answers and this is a lot of work since there are usually hundreds of HWs to grade. We should warn you that a few points will be deducted if you don't number the pages correctly.

To turn in your work, your document needs to be in PDF format. If you're using Word, once you've saved your document, you can export it as a PDF in the File ❯ Export menu; alternatively, you can go to File ❯ Save As and choose "PDF" in the drop-down menu near the bottom. Once you've done this, open the Math 18 MATLAB course on Gradescope, find Assignment 1, and submit your PDF for this assignment.

After you have saved and uploaded your lab document, remember to log out of your PC.

A few final comments and warnings:

  1. The labs are designed to be completed on specific ETS lab PCs. Use home versions of MATLAB or versions on ETS Macintoshes at your own risk.
  2. TAs are available for help during lab time, not via email the night before the assignment is due.
  3. No emailing labs to TAs.

The future labs will contain most of the applications of linear algebra to be found in Math 18. These problems can take a little while to work out. Be warned that future labs will be longer than this one! Don't wait until the last minute to start.

Last Modified: 8 January 2017