AMATH 352
Summer Quarter, 2008

Applied Linear Algebra and Numerical Analysis



MATLAB Reference Page

One equals sign (=) versus two (==)
Relational operators
Logical operators
if statements

One equals sign (=) versus two (==)

When writing Matlab programs, sometimes you have to use two equals signs instead of one. One equals sign by itself (=) is for assignment. Whenever this shows up, it's telling Matlab to assign the value on the left to the variable on the right. So, for instance,
>> x = 3;
assigns the value 3 to the variable x, which you see in the output. On the other hand, if I try to say
>> 3 = 3
I get an error:
??? 3 = 3
     |
Error: The expression to the left of the equals sign is not a valid target for an assignment.
This is because whatever's on the left side of = has to be a variable.

The double equals sign (==) is used for checking whether a relation is true. As such, it's called a relational operator. I can use this in the place I couldn't use = above:

>> 3 == 3
This produces the output
ans =
     1
because the relation is true. In the meantime, if I say
>> 2 == 3
I get the output
ans =
     0
because the relation is false.


Relational operators

Here's a list of the relational operators in Matlab. You'll use these whenever you write if statements or while loops.
== equals
~= does not equal
>= greater than or equal
<= less than or equal
> strictly greater than
< strictly less than


Logical operators

You can use logical operators to test several relations at once. In the code you'll write for this class, it's a lot more likely that you'll use 'and' than 'or.' (There's also one for 'not', but to be honest, I've never used this in mathematical code.)
&& and
|| or


if   statements

The if statement is how you write commands that will only be executed under certain conditions. The general form is
if expression
   statements
end
Here expression is generally a logical relation that you're testing, and statements is the code you want to execute if expression is true. For example, here's a gratuitous if statement that adds 1 to the value of x if x > 3:
if (x>3)
  x = x+1;
end
Now say I want my if statement to only execute of 3 < x 4.  I can do this using the logical 'and' operator, &&.
if (x > 3) && (x < 4)
  x = x+1;
end