COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
COMPUTATIONAL MATHEMATICS AND
COMPUTER ARCHITECTURE
Topic 09 – MATLAB Programming
Our vision is to be Singapore’s private education institution of choice, and
we are committed to helping our students achieve their career and
educational goals through lifelong learning opportunities.
We build futures, one success story at a time.
Integrity . Knowledge . Support . Opportunity . Results
Topic 09 – MATLAB Programming
• Upon successful completion of this topic, students should be able to:
• Describe the use of control structures
• Describe the use of sequence statements
• Describe how to use selection statements
• Describe how to use repetition statements
KHE-LCD-SGD-00233 1
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
MATLAB
MATLAB CONTROL STRUCTURES
Simple Flow Chart
Dine in? Y N Order from
Panda?
Grab
N Y
N Drive? Order from
Panda
Put on Start car
walking
shoes
KHE-LCD-SGD-00233 2
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
MATLAB – Control Structures
• Programs often requires examining conditions to decide on which course of
action to take.
• The flow chart demonstrates that control structures are needed on how the
program shall proceed based on decisions made
MATLAB
MATLAB SEQUENCE STATEMENTS
KHE-LCD-SGD-00233 3
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
MATLAB – Sequence Statements
• Sequence statements are the default mode of operation for any program. It is not
implemented with any special keywords.
• Sequence statements can be thought of as a cooking recipe that follows the recipe
step by step. For Example:
Step 1
Stir sugar, cream, and milk into a saucepan over low heat until
sugar has dissolved.
Step 2
Transfer cream mixture to a pourable container such as a large
measuring cup.
MATLAB – Sequence Statements
• An example of sequence statements in program is often seen as one line
being executed after another
• Example:
total = 50 + 30 + 45;
average = total / 3;
fprintf("Average of 3 numbers is: %d\n", average);
KHE-LCD-SGD-00233 4
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
Sequence Statement Output
• Average of 3 numbers is: 4.166667e+01
MATLAB – Sequence Statements
• Sequence statements are easy to understand. However, they show only
one way for a program to proceed.
• A useful program rarely has just a single flow. It would allow users to make
decisions.
• Hence there are 2 other structures: Selection and Repetition Structures
10
10
10
KHE-LCD-SGD-00233 5
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
MATLAB
SELECTION STATEMENTS
11
MATLAB – Selection Statements
• A MATLAB program has Selection statements using one of the following
structure:
-if statement
-if … else statement
-if … elseif … else statement
-switch … case
12
12
12
KHE-LCD-SGD-00233 6
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
MATLAB – Selection Statements – if statement
• A single if statement is used if a condition applies and if nothing else will be
applied if the condition is not met:
-An example is when a person is a member and he/she is entitled to say 10%
discount. If the person is not a member, then the discount does not apply.
price = 100;
is_member = true;
if is_member
price = price * 0.9;
end
fprintf('Price to pay is %.2f\n', price);
13
13
Selection Statement Output
• Price to pay is 90.00
14
14
KHE-LCD-SGD-00233 7
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
MATLAB – Selection Statements – if – else statement
• An if-else statement is used if a condition applies, an action must be
performed and if the condition does not apply, another action must be
performed. An example is trying to determine whether the person is eligible
to start work in Singapore.
age = 16;
if age > 16
fprintf('You are %d and ready to work!\n', age);
else
fprintf('No work for you as you are only %d\n', age);
end
15
15
Selection Statements – if – else statement Output
• No work for you as you are only 16
16
16
KHE-LCD-SGD-00233 8
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
MATLAB – Selection Statements – if – elseif statement
• An if-elseif statement is used if there could be multiple conditions to be tested but only 1 set
of actions can be executed. An example is trying to determine the grade of a Special paper
taken in ‘Advanced Levels’
score = 75;
if score > 75 && score <= 100
fprintf('Grade is Distinction!\n');
elseif score >= 50 && score <= 75
fprintf('Grade is Merit\n');
elseif score >= 0 && score < 50
fprintf('Grade is Fail\n');
else
fprintf('Invalid score!\n');
end
17
17
Selection Statements – if – elseif statement Output
• Grade is Merit
18
18
KHE-LCD-SGD-00233 9
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
MATLAB – Selection Statements – switch – case statement
• A switch-case statement is sometimes used over if-else statements due to
readability.
• It would be intuitive to use switch-case if you are testing a single variable
and it has discrete values.
• An example would be trying to determine the discount based on the number
of rides to be taken
19
19
MATLAB – Selection Statements – switch – case statement
(2)
num_rides = 3;
discount = 0;
switch (num_rides)
case 1
discount = 10;
case { 2, 3 }
discount = 20;
case 4
discount = 30;
otherwise
discount = 5;
end
disp(discount);
20
20
KHE-LCD-SGD-00233 10
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
Selection Statements – switch – case statement Output
• 20
21
21
MATLAB
REPETITION STATEMENTS
22
KHE-LCD-SGD-00233 11
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
MATLAB – Repetition Statements
• A MATLAB program can repeat statements using one of the following
repetition structures:
-for... end
-while … end
23
23
MATLAB – for loop – Known number of repetitions
• A for loop is used in situations where the number of repetitions is known:
-One such example is to print all numbers in a range (1 to 5)
for n=1:5
fprintf('%d \n', n); % 1 2 3 4 5
end
-Another such example is to print all numbers in a range (1 to 20), skipping 2 numbers in
between
for n=1:3:20
fprintf('%d \n', n); % 1 4 7 10 13 16 19
end
24
24
KHE-LCD-SGD-00233 12
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
MATLAB – for loop – Known number of repetitions (2)
• A for loop can also be used with a vector:
-Example with a vector
vec = [1, 3, 8, 5];
for n=1:length(vec)
fprintf('%d \n', vec(n)); % 1 3 8 5
end
25
25
MATLAB – for loop – Known number of repetitions (3)
• A for loop can also be used a matrix:
-Example with a matrix
my_mat = [3, 6, 9; 2, 4, 6];
[rows, cols] = size(my_mat);
for row=1:rows
for col=1:cols
fprintf('(%d) ', my_mat(row, col));
end
fprintf('\n');
end
% (3) (6) (9)
% (2) (4) (6)
26
26
KHE-LCD-SGD-00233 13
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
MATLAB – while loop – Unknown number of repetitions
• A while loop is typically used in situations where the number of repetitions is typically
unknown:
-Example: Request the user to key in some numbers or 0 to quit
count = 0
num = input('Enter any number or 0 to exit: ');
while num ~=0
count = count + 1;
num = input('Enter any number or 0 to exit: ');
end
fprintf('You entered %d numbers\n', count);
27
27
MATLAB – while loop – Unknown number of repetitions (2)
• A sample output:
Enter any number or 0 to exit: 1
Enter any number or 0 to exit: 2
Enter any number or 0 to exit: 3
Enter any number or 0 to exit: 4
Enter any number or 0 to exit: 5
Enter any number or 0 to exit: 6
Enter any number or 0 to exit: 8
Enter any number or 0 to exit: 0
You entered 7 numbers
28
28
KHE-LCD-SGD-00233 14
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
MATLAB
COMBINING SELECTION WITH REPETITION
29
MATLAB – Combining Selection With Repetition
• Write a program that counts odd and even positive numbers from a vector.
numbers = [52, -35, 12, -31, 1, 33, 20, 6];
Step 1: Firstly let us declare some 2 variables to count the positive odd
numbers and positive even numbers
positive_odd_count = 0;
positive_even_count = 0;
30
30
KHE-LCD-SGD-00233 15
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
MATLAB – Combining Selection With Repetition (2)
• Step 2: Loop through the vector to look into every item
for number=numbers % iterate through each item
...
end
Step 3: In the loop, check that the numbers are positive first before checking they
are odd or even.
if number >= 0 % check for positive numbers
% check for odd or even
end
31
31
MATLAB – Combining Selection With Repetition (3)
• Step 4: Count the odd and even numbers
if rem(number, 2) == 0
positive_odd_count = positive_odd_count + 1;
else
positive_even_count = positive_even_count + 1;
end
Step 5: Print the results AFTER the loop
fprintf("Number of positive odd numbers: %d\n",
positive_odd_count);
fprintf("Number of positive even numbers: %d\n",
positive_even_count);
32
32
KHE-LCD-SGD-00233 16
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
MATLAB – Complete Listing
numbers = [52, -35, 12, -31, 1, 33, 20, 6];
positive_odd_count = 0;
positive_even_count = 0;
for number=numbers
if number >= 0
if rem(number, 2) == 0
positive_odd_count = positive_odd_count + 1;
else
positive_even_count = positive_even_count + 1;
end
end
end
fprintf("Number of positive odd numbers: %d\n", positive_odd_count);
fprintf("Number of positive even numbers: %d\n", positive_even_count);
33
33
MATLAB – Combining Selection With Repetition Output
• Number of positive odd numbers: 4
• Number of positive even numbers: 2
34
34
KHE-LCD-SGD-00233 17
COMPUTATIONAL MATHEMATICS AND COMPUTER ARCHITECTURE
Summary
• MATLAB, like majority of the programming languages have control
structures
• The default mode for MATLAB is sequential execution.
• To cater to alternate flows, MATLAB also provides selection and repetition
structures like most programming languages
35
35
35
Thank you
36
KHE-LCD-SGD-00233 18