# Flow Control in Matlab

## Conditionals

It is common in programming to need to use
logical tests. These expressions have *boolean* values;
i.e. they evaluate to either 'true' or 'false'.
In Matlab, 'true' is represented by an integer 1, and 'false'
by 0. Thus, one might examine an expression as follows.

>> K = -1 K = -1 >> K < 0 ans = 1 >> K > 0 ans = 0

One must be able to evaluate complicated logical expressions
for a number of mathematical tasks. Matlab, like all programming
languages, provides a full ensemble of logical operators for that
purpose.

Binary Operator | Meaning |
---|---|

== | Is equal to |

< | Is less than |

> | Is greater than |

<= | Is less than |

>= | Is greater than or equal to |

~= | Is not equal to |

&& | And |

|| | Or |

>> a=-1; b=1; c=0; >> c==0 ans = 1 >> c==a ans = 0 >> a<b ans = 1 >> a>=c ans = 0 >> a<b && a>=c ans = 0 >> a<b || a>=c ans = 1 >> a<b || (a>=c && b<c) ans = 1 >> (a<b || a>=c) && b<c ans = 0

Matlab has the usual compliment of flow control statements, allowing the
usual program looping and decision structures

## for

If you want to perform some operation a specific number of times then you should use a 'for' construction. In Matlab, the for loop has the formfor

*variable*=

*range*

*Put commands to be repeated here*

end

Here is an example that computes the factorial

`fact`of a number

`K`.

fact = 1; for i=2:K fact = fact*i; end

## while

If you need to perform some operation an unknown number of times, until some condition is satisfied, then you should use a 'while' construction. It is worth stressing the difference in usage between this and 'for'. Use a 'for' loop when you know ahead of time how many times you must do something, but use a while loop when you need to do it until some criterion is false.while

*condition is true*

*Put commands to be repeated here*

end

Here is an example in which we find the largest power

`n`of 2 that is less than or equal to a given positive number

`K`.

n = 0; while 2^n <= K n = n+1; end % 2^n is now greater than K, so reduce it. n = n-1;

## if

The 'if' construction is not for repeated operations at all.
Instead, it is simply a way to have your program make decisions.
If some condition is true, then do one set of things; if not
perhaps do something else, or skip the actions.

if *condition is true*

*Put commands to be performed once here*

elseif *different condition is true*

*Put commands to be performed once here*

else

*Put commands to be performed once here*

end

The `else` and `elseif` statements are optional.
If it suits your code, the construction could be as simple as
if *condition* commands; end.

`K < 0`. Here is an 'if' construction to throw an error if

`K`is negative.

if K<0 error('K must be non-negative.') end;

Assignment 7 is posted.

A solution to the
exam has been posted.