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 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 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

Pages: 1 2 3 4