Controlling Flow
The if statement is a decision-making statement. In its simplest form, it looks like this:
if (x > 0) zz = 1/x; end
The expression “x > 0” controls what the rest of the statement will do. The command “zz = 1/x” is executed only if the condition “x > 0” is true.
if (x > 0) zz = 1/x; else zz = -1; end
Comparing two numeric values uses one of the following relational operators. All of comparison operators return a value of 1 if the comparison is true, or 0 if it is false.
Comparison | Operation |
x == y | x is equal to y |
x ~= y | x is not equal to y |
x > y | x is greater than y |
x >= y | x is greater than or equal to y |
x < y | x is less than y |
x <= y | x is less than or equal to y |
Further branches. When more than two branches are necessary, "elseif" can be used.
if (i - j == 0) B(i,j) = 1; elseif (i - j == 1) B(i,j) = -1; else B(i,j) = 0; end
The for statement makes it convenient to execute a routine repeatly while counting iterations of a loop. It looks like this:
for i = 1:5 x(i) = i^2; end
The above code works by first evaluating the expression 1:5 to produce a range of values from 1 to 5. Then the variable i is assigned the first element of the range and
x(i) = i^2;in the loop is executed once. And this process continues until there are no more elements to assign for i.
© TTU Mathematics