Next: Scripts and functions Up: Programming in Matlab Previous: Programming in Matlab

## Conditionals and loops

Matlab has a standard if-elseif-else conditional; for example:

```>> t = rand(1);
>> if t > 0.75
s = 0;
elseif t < 0.25
s = 1;
else
s = 1-2*(t-0.25);
end
>> s
s =
0
>> t
t =
0.7622```
The logical operators in Matlab are <, >, <=, >=, == (logical equals), and `~=` (not equal). These are binary operators which return the values 0 and 1 (for scalar arguments):
```>> 5>3
ans =
1
>> 5<3
ans =
0
>> 5==3
ans =
0```
Thus the general form of the if statement is
```if expr1
statements
elseif expr2
statements
.
.
.
else
statements
end```
The first block of statements following a nonzero expr executes.

Matlab provides two types of loops, a for-loop (comparable to a Fortran do-loop or a C for-loop) and a while-loop. A for-loop repeats the statements in the loop as the loop index takes on the values in a given row vector:

```>> for i=[1,2,3,4]
disp(i^2)
end
1
4
9
16```
(Note the use of the built-in function disp, which simply displays its argument.) The loop, like an if-block, must be terminated by end. This loop would more commonly be written as
```>> for i=1:4
disp(i^2)
end
1
4
9
16```
(recall that 1:4 is the same as [1,2,3,4]).

The while-loop repeats as long as the given expr is true (nonzero):

```>> x=1;
>> while 1+x > 1
x = x/2;
end
>> x
x =
1.1102e-16```

Mark S. Gockenbach
Wed Sep 8 10:44:13 EDT 1999