Week 1 Coding Lecture 1

How to read these notes

Coding lecture notes for this class will (mostly) be written in MATLAB live scripts, and then converted to PDF in order to mix codes and exposition. For example, try the code below on the MATLAB command window.
He wanted it that way.
If you run that command a few times you will notice that you get a different answer.
I will sometimes include code that is intentionally broken to illustrate an error. For example, this code tries to use a variable that has not yet been defined. Try it on the command window and see what error it gives you.

Writing your own code

There are three ways to write code in MATLAB: Command line (in the command window), as scripts, or as functions.
The command window is good for quick calculations (for example to test a small piece of code), but it has some serious drawbacks. For one thing, you can't edit and rerun code you have already typed in the command window. Instead, you just have to retype it at the prompt. For another, nothing in the command window is saved when you exit MATLAB. You have to redo all work from the command window every time you start.


Since the command window is so limited, you should write most of your MATLAB code in scripts (files with a .m extension). You can make a new script with the "New Script" button in the top left corner of the program.
Scripts are essentially just the code blocks from a live script like this one, without the text in between. Try opening a script, typing the line "why()" (without quotes) and saving it with the name "my_script.m" (again, without quotes). You can run the code in this script by clicking the Run button (with a green arrow) or by typing the name of the script without the .m extension in the command window. The output will appear just as if you had typed each line of the script into the command window.
This example only has a single line, but in general your scripts will contain many lines of code. MATLAB runs each line in order from top to bottom. (Next week we will learn how to make MATLAB repeat or skip lines of code.)
(Side note: There are a few rules to naming scripts. The file name can only contain letters, numbers and underscores, and it must start with a letter. Names are also case sensitive, so my_script.m and My_Script.m are two different files. If you forget these rules and start a file name with a number or include a space, then you will get somewhat cryptic error messages.)


It is often useful to leave explanatory text in a script. If you begin a line of code with a percent sign and a space, then MATLAB will ignore all text on the line when running the code. This is useful for leaving notes or explanations for yourself (or for anyone else who may read your code later).
% This is a comment. Matlab will ignore it
% when you run this code block.
If you start a line with two percent signs and a space, then it creates a section break. These section breaks work just like the horizontal lines in a live script and let you use the "Run Section" button to just run pieces of your code at a time. However, I have a very old school style of coding (because I learned how to program in C/C++ and then learned Java and MATLAB and also a bit of Assembly at the same time), so I never use section breaks.

Basic calculation

You can use MATLAB as a very expensive calculator. You are probably familiar with all of the syntax already, but here are some examples:
1 + 3
ans = 4
4 - 5
ans = -1
2 * 3.2
ans = 6.4000
4 / 3
ans = 1.3333
ans = 125
3 - 2*6
ans = -9
8 * (1 + 2)
ans = 24
pi + 2
ans = 5.1416
As you can see, MATLAB uses standard symbols for all of the basic mathematical operations and follows the usual order of operations. MATLAB also has a few common constants defined by default. We used pi above, but there are a few others like the imaginary unit i and infinity Inf. MATLAB also has all the usual scientific calculator functions like sin, cos, tan, log, etc. For example,
ans = -0.5440
ans = 1
When you run this section, you will see that MATLAB displays the output as ans = 1 (or whatever other number was produced). ans is the name Matlab uses to store the last thing that was calculated. The value is saved in memory and not just printed as output. You can see this by looking in the workspace (which should be beside the command window in the main MATLAB screen). You should see an entry in the workspace with name ans and value 1.


ans is our first example of a variable. (Actually, pi is also a variable.) Variables are values that MATLAB stores in memory so that we can use them later. For example, we know that the line
2 + 2
ans = 4
sets the value of ans to 4. We can then use this value in other calculations. For example, we could calculate 4 * 2 by writing
ans * 2
ans = 8
When MATLAB sees the name ans, it checks the workspace to find the value of the variable, then replaces ans with the value it found.
It is important to emphasize that this is just an example of the concept and ans is a very bad choice of variable for any real computation. (In fact, MATLAB should show you a warning when you try to run this code.) To see why, notice that the value of ans is now 8, so if we now try the code
ans * 2
ans = 16
a second time, we get a different answer. The problem is that MATLAB is constantly overwriting the variable ans, so we have very little control over what value is actually in it.
As a rule of thumb for beginners, don't use ans as a variable.


It is much more convenient to be able to make our own variables and not rely on automatic versions like ans. To this end, we can use the assignment operator = to assign numbers to variables. The = symbol means "calculate the value on the right and assign it to the name on the left". For example,
x = 8
x = 8
Assigns the value 8 to a variable named x. After running this code, you should see x appear in the workspace along with ans. We can now use the variable x in calculations and MATLAB will treat it as if we typed 8. For instance,
x / 2
ans = 4
Unlike the variable ans, x will not be overwritten automatically, so we can keep using it in multiple lines without worrying that its value will change.
x + 3.6
ans = 11.6000
x - 2
ans = 6
x * 5.0
ans = 40
Notice that x is just replaced with 8 in all of these calculations.
If we want to change the value of x, we can just reassign it with the = operator.
x = 3
x = 3
The value of x is now 3 instead of 8. This doesn't change any old results (the output from previous lines is the same) but all future occurrences of x will use the new value. For example,
x + 3.6
ans = 6.6000
x - 2
ans = 1
x * 5.0
ans = 15
There is no reason to restrict ourselves to just one variable. We can make many different variables, as long as they each have a different name. (Side note: Just like with file names, MATLAB has a few rules for naming variables. Variable names can be as long as you want and can contain letters, numbers and underscores, but they must start with a letter. This means that x, answer_number_4 and int2str are all valid variable names, but 3test, x-y and answer number 4 are not. Names are also case sensitive, so ans1 and Ans1 and ANS1 are all different names. That said, it is not a good idea to have different variables that differ only by case. There are also a few reserved words that MATLAB uses for other purposes and you cannot use as variable names. For example, function, for, while, if and end are all reserved words. MATLAB will give an error if you try to use one of these as a variable name.)
As an example,
x = 8
x = 8
y = 3
y = 3
var3 = 0
var3 = 0
We can combine these variables just as if they were numbers.
z = x - y + 2^var3
z = 6
As we have already seen, you can't use a variable until you have assigned it a value. If you try to do a calculation with a variable that you haven't yet defined, MATLAB will give an error along the lines of "undefined function or variable". For example, try running this in the command window:
3 * N
It is important to remember that the assignment operator is not the same thing as mathematical equality. In particular, it treats variables on the left and right side differently. If a variable appears on the right side of an = operator, MATLAB replaces it with whatever value it finds in the workspace, so the x - y + 2^var3 above is replaced with 8 - 3 + 2^0. On the other hand, if a variable appears on the left side then MATLAB does not look up its value. Instead, MATLAB stores the value on the right in the variable named on the left. One example that comes up a lot is
x = 8
x = 8
x = x + 1
x = 9
The last line doesn't make any sense in mathematics, but it is perfectly sensible code. MATLAB evaluates this expression as follows: First, it sees an x on the right side of the = operator, so it looks up its value in the workspace. Since x has the value 8, MATLAB interprets the right side as 8 + 1, which is 9. Next, MATLAB sees the name x on the left side of the = operator, so it stores the value 9 in the variable named x.
There are a few things worth remembering about assignment and variables in MATLAB:

Output suppression

You have probably noticed by now that most lines of code in MATLAB cause some sort of output to be printed in the command window (or in the live script). This is useful behavior when you are testing or fixing code, but it is actually quite undesirable in general.
One issue is that it quickly becomes difficult to find relevant information in the command window when it is cluttered with output. More importantly, printing output is actually substantially slower than most other work that your code might be doing. We will see examples later in the class where printing the output takes hundreds or thousands of times longer than calculating the answer. It is therefore useful to be able to tell MATLAB not to print the output from certain lines of code.
This is what the semicolon ; is for in MATLAB. If you end a line of code with a semicolon, then MATLAB does exactly the same thing it would have without the semicolon, but it does not print the output. For example,
x = 1
x = 1
y = 2;
Notice that the first line prints "x = 1" when you run it, but the second line doesn't print anything. If you look in the workspace, though, you can see that both x and y have been defined, so we know that MATLAB still ran both lines of code.
As a general rule, when you are finished with a script it should run without printing any output, except possibly the final answer. This means that you should end every single line with a semicolon. (Actually, some lines don't need a semicolon because they don't print output by default. For example, the line clear all doesn't print anything, so a semicolon is unnecessary. That said, it never hurts to end a line with a semicolon.) This will become quite important in future assignments, where printing output will drastically slow down your code. If you want to print out the value of a variable, you can just write the variable name on its own line without a semicolon, or you can use the disp function. For example:
x = 1
The only difference is that disp does not print the "x = " part.
A semicolon also indicates the end of a line of code. This means that you can put more than one line of code in a single line of text if you end each part with a semicolon. For example, instead of writing
a = 1;
b = 2;
c = 3;
you could write
a = 1; b = 2; c = 3;
This is almost always a bad idea. There are only two times when this method is worth doing. One is when you have to define a lot of variables at the beginning of a problem (like the example above with a, b and c) and the other is when you have some short boilerplate code that always comes together.