- Matlab - https://matlab.diyez.net -

Matlab Tutorial 7: Common Programming Structures and Conditional Statements

In this tutorial we will deal with some common programming structures and also alternative conditionally statements. These statements exist as well in almost all high-level programming languages. In Matlab [1] a common programming construction is a if or a switch statement. To repeat a number of statements, can be solved with a for or a while [2] loop.
In the following examples we will see how this is implemented in Matlab, but nevertheless how good programmers we are, some mistakes will happen. This also motivates a brief view of the debugger in Matlab.

For Loop in MATLAB

The general expression for a for-loop is:

for variable=expression
control statements
end

Example 1:

Let us write an m-file that calculates the sum: The sum to be calculated is: 1+1/22+1/32+…..+1/102.

i=1;
the_sum=0;
for i=1:10
the_sum=the_sum+1/(i^2);
end
fprintf('The sum of 10 elements gives: %f ', the_sum)

The execution of the code in Matlab command window gives: The sum of elements gives: 1.549768

The variable expression assigns a value to the loop variable, one start value and one end value, if nothing else is given assume increment 1 (for i=1:10).
The control statements can be expressed with more arbitrary expressions.

Example 2:

% The m-file The_sum.m calculates the five first odd elements i=1,3,5,8,9
% Below follows The_sum.m.
i=1;
the_sum=0;
disp('i the_sum')
disp('-----------')
for i=[1 3 5 8 9]
the_sum=the_sum+1/(i^2);
fprintf('%2u %7.2f \n',i,the_sum)
end

After callling the the m-file The_sum we get:

i the_sum
------------
1 1.00
3 1.11
5 1.15
8 1.17
9 1.18

While Loop in MATLAB

In a while loop the statements are repeated as long as the logical condition are true.
A while loop has the following the structure:

while logical expression
statements
end

If the logical expression is true, then the statements are executed. hen once again we evalute the logical expression and if still true then we repeat the statements. This continues until the logical expression becomes false. If the statement is false from the start, the loop is not entered.

Example 3:

Let us illustrate how to use a while-loop.

% The m-file count_up.m
j=0
while j<8
j=j+1;
disp(j)
end

Test and check to see what the m-file count_up does! Are there any surprises?
In order to produce the output we need 8 times to evaluate the expression j<8. Often one compares two numbers in these evaluations. In Matlab we have 6 operators to be used in comparison. < Less than > Greater than == Equal <= Less tham or equal. >= Greater than or equal ~= Not equal If the logical expression is true, then it gets the value 1 and the statements that follows will be performed, otherwise 0.

If-else in MATLAB

It is sometimes needed to have alternatives in programming. In Matlab this is achieved by if and else conditions or switch statements. See the following example:

if t==1 % if t=1, then increment h with one.
t=t+1;
else % else display the text ”Hello”.
disp('Hello')
end

The syntax looks like:

if logical expression
statement1
else
statement 2
end

If the logical expression is true then the statement 1 is carried out, but if the logical expression is false then statement 2 will be executed.There could of course be many statements to be done for each alternative.
Suppose one needs several alternatives instead of two. In that case syntax looks is:

if logical expression 1
statement 1
elseif logical expression 2
statement 2
.
.
elseif logical expresion n
statement n
else
statement n+1
end

Only one of the alternatives must be true otherwise the final statement n+1 will be performed.

Example 4:

We will now examplify this with a m-file. It requests temperatures from the keyboard and if we enter negative values (in degree Celsius) the answer will be ‘Freezing cold’. Temperatures above 25 gives the answer ‘Very hot’ and for all other inputs the reply will be ‘Temperature is OK!’ . The example is of course a very swedish one.

% M-file temperature.m
temp=input('Give a temperature !')
if temp<=0
disp('Freezing cold!')
elseif temp>25
disp('Very hot!')
else
disp('Temperature is OK')
end

The m-file above can deal with all temperatures given with numbers. One limitation is that we need to call it every time we want to decide the temperature. This can be improved by using a while loop outside the if and else structure.
We can have nested structures in Matlab.

Switch in MATLAB

Another way of performing evaluation of conditions is to use a switch and case structure. When we execute the structure, one case are supposed to be true and the corresponding statement is done. On the other hand if none of the cases are equal to the expression, then otherwise is valid.
The syntax is:

switch expression
case value 1
statement 1
case value 2
statement 2
.
.
case value n
statement n
otherwise
statement n+1
end

Above the expression is compared to all the cases if none of these are equal with its corresponding value then otherwise. By using the case alternatives we can also compare with several values at the same time.

Example 5:

In this example we will try if a dice has an odd or an even number. We will write a function m-file to decide this.

% M-file dice.m
function dice(number)
switch number
case{1,3,5}
disp('Odd number !')
case{2,4,6}
disp('Even number !')
otherwise
disp('This is no ordinary dice !')
end

Try your m-file with: dice(3), dice(6) and dice(8) !

Interrupt commands in MATLAB

In some cases we must have the option to interrupt the execution of the m-file. This could be due to error in keyboard input or some other obvious wrong calculation result or maybe just a need to pause the execution.
error(‘string’) Interrupts an m-file execution and writes the message ‘string’ in the command window.
Pause Pauses the execution and waits for a keyboard input or a timeout.
Break Interrupts while- and for-loops. If we have nested loops it only breaks the closest one.
In the examples below I will try to examplify how error and break can be used.

% M-file nonsens.m
disp('To continue, press a button !')
pause
disp('Answer the question with Y/N !')
str=input('Do you feel alright ? ','s');
if str=='Y'
disp(' Yes, I feel alright !')
elseif str=='N';
disp('No, I don’t feel alright!')
else
error('Wrong answer !')
end

Save the m-file! We will use it later.

% M-filen random.m
% Examplify how break command works.
t=0;
while t<inf
number=input('Give a number ! (-1 to stop) ');
t=t+number
if number==-1
break
end
end

Nested loops in MATLAB

Nested for and while-loops can occur in Matlab. The structure is shown below. Suppose we have created a matrix [3] A=[1 2 3; 4 5 6]. Now we would like to write the elements row-wise from the matrix A.

for k=1:2 % row index
for j=1:3 % column index
disp(A(k,j))
end
end

Try it!
I do not think it will surprise you. Try also to change the program so the elements in the matrix A are written column-wise.
The structure for a nested while loop looks like:

while logical expression 1
statements 1
while logical expression 2
statements 2
end
statements 3
end

Try-catch-end in MATLAB

A try catch end statement is useful if there is any possibility of that an error might occur. The statements are executed in order and starting from the top. If there an error occurs in one of the statements1 the program is not terminated. Instead the error message is stored in ‘lasterr’ and the program continues with statements 2.
The syntax is:

try
statements1
catch
lasterr % Gives the last error message in Matlab.
statements2
end

Where we want to divide two numbers with each other, but we still want the program to continue. No matter if we enter a letter or any non-number character.

Example 6:

Read 2 numbers and divide them to each other!

Q=input('Give the numerator : ');
P=input('Give the denominator: ');
try
quotient=Q/P;
catch
lasterr
quotient=0;
end
disp(quotient)

What happens if we enter two numbers? Try to enter a letter or some other character!

Debuggingin MATLAB

No living human being writes programs without any errors. It could be simple syntactic errors or more complicated ones as logical errors. Matlab is equipped with a debugger to help the programmer to find the error. The simplest form of debugging is to put % ( makes it a comment) in front of the command line and then step by step add one command line at a time and see if the program works as intended. Maybe try with certain data that gives answers that you know are correct.
Nevertheless how extensive tests we make of our program. We can not claim with 100% certainty that the program is accurate, unless it is a very small and simple program. The errors could be we are using small letters instead of capital letters, some variables are undefined or the variables have previous values that we have disregarded.
Common mistakes are a forgotten parenthesis or operator, but the most serious ones are the logical errors. The algorithm we are using are wrong and the program is executable and delivers wrong answers. These kind of errors can be very tough to detect.
Now let us move on and see how we can use the debugger. Put the program below in the editor. In the edit window you can easily find the symbol button for the debugger (white sheet with a red dot).
Click on every command line in your m-file!
Now there will be a red dot on every single line. This is a breakpoint.
Whenever you run the program in debugging mode the program will stop at every breakpoint it will find in the program.
In our case it will stop at every line.

% M-filen nest.m
A=[ 1 2 3; 4 5 6] % We have a 2-dimensional matrix here.
for k=1:2 % row index
for j=1:3 % column index
disp(A(k,j)) % display the matrix element
end
end

In the command window you can notice that the prompter is changed from >> to K>>. Run the m-file and go from one breakpoint to another by the F10 button in the command window. The result is shown in appendix A. Notice also how it looks in the edit window. There is a green arrow indicating what line that is executed at the present. By placing the mouse cursor over a variable name the value for each is shown.
Whenever you want to leave the debugging mode just click on the same button that started the debugger.

Timing

In some cases there could be limitations of time. How long a certain calculation are supposed to continue and therefore Matlab provides us with a tool to find out what parts of a program that are time-consuming. This is accomplished by the command profile.
Let us have a look on our previously used m-file nonsens. Write!

profile on % starts timer
nonsens
profile off
profile report % Opens a html-page, where you can find a table.
% Click on the link nonsens.
% Consumed time for each command line are shown.

Logical operators
& Logical and
| Logical or
~ Logical not
Finally we will look on three examples to see how we can use these operators.

% Logical AND
x=input('Give a x: ')
k=input('Give a k: ')
if x==3&k<100 % if x=3 and k<100, then display ”Hello !”
disp('Hello !')
else
disp('Hi !') % otherwise display ”Hi !”
end
% Logical OR
x=input('Give a x: ')
k=input('Give a k: ')
if x==3|k<100 % if x=3 or k<100, then display ”Hello !”
disp('Hello !')
else
disp('Hi !') % otherwise display ”Hi !”
end
% Logical NOT
k=input('Give a k: ')
if ~(k<100) % if k>=100, then display ”Hello !”
disp('Hello !')
else % otherwise display ”Hi !”
disp('Hi !')
end