Sequences and loops
Matlab can execute a sequence of commands typed in the command window separate by semicolons (;)
>> borrowed = 123.00; interest = 0.02; repayment = borrowed + (borrowed * interest);
The sequence of commands is executed when you press [Return]
. Pressing [Shift][Return]
starts a new line without executing the one above - when you finally press [Return]
then all the lines you have typed will be executed.
Loops
The simplest sort of loop to describe is one that is executed a fixed number of times. Programmers call this a 'for loop' and here is a very simple example:
>> for ii=1:3; disp(2^ii); end
2
4
8
This type of loop repeats the commands that are inside of it a fixed number of times. The basic syntax is:
for <list-or-range-of-values>
<instruction-block>
end
The three elements of the loop can be on different lines or on the same line separated by semicolons.
As you can see we have the for
statement, and an end
statement which together tell Matlab where the loop starts and finishes. The instruction block can consist of as many statements as we like. We need two more things, a variable to holds the loop information and a range of values for this variable. We have called the variable ii
here (any valid variable name is fine) and the range of values that ii
can take is written 1:3
meaning 'starting at one and ending at three'.
More complex example:
% for loop doing a calculation
total = 0;
for kk = [1 3 5 7 9]
total = total + kk;
end
% display the total
disp(total);
As you can see we have the for
statement and the end
statement again. The instruction block is a single line. We have called the loop variable kk
and the range of values is [1 3 5 7 9]
meaning the loop is repeated 5 times with kk
taking these 5 values.