AMATH 352
Summer Quarter, 2008
>> 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 = 3I 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 == 3This produces the output
ans =
1
because the relation is true. In the meantime, if I say
>> 2 == 3I get the output
ans =
0
because the relation is false.
| == | equals |
| ~= | does not equal |
| >= | greater than or equal |
| <= | less than or equal |
| > | strictly greater than |
| < | strictly less than |
| && | and |
| || | or |
if expression statements endHere 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; endNow 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