BasicMDL 4 ProgramDev

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 55

MATLAB Programming Fundamentals I

(Program Design and Development)

Dominic C. Ezugworie
chidominez@gmail.com
+234 (0) 703 907 1904

© 2012 Dominic C. Ezugworie


Where we are Headed ...

2
Recap of syntax basics
• Create/Define variables By assigning values
– Discreetly
A = 100; % remember the effect of not suppressing output
– As the result of expression
B = 3^2 + 3*2 + 2;
– Remember naming rules
– Variables must be defined before use
– No special declaration or dimensioning statements

• Create numeric arrays


– Discreetly
C = [12, 62, 22; 16, 87, 43; 17, 95, 6];
– Using functions
D = magic(5);
3
Recap of syntax basics
• Store text in character strings
myString = 'Hello, world';
• Enter multiple statements on one line
A = magic(5), B = ones(5) * 4.7; C = A./B
– MATLAB interprets from left to right
– Following operator precedence

4
Recap of syntax basics
% Continue long statements on multiple lines
s = 1 - 1/2 + 1/3 - 1/4 + 1/5 ...
- 1/6 + 1/7 - 1/8 + 1/9;
% this is wrong
mystring = 'Accelerating the pace of ...
engineering and science'
% this is right
mystring = ['Accelerating the pace of ' ...
'engineering and science'];
% an ellipses outside a quoted string is
equivalent to a space
5
Recap of syntax basics
• Call a function supplying argument, separating
arguments with comma, returning values in variables
max(A); max(A,B); maxA = max(A);
• Choose between command syntax and function
syntax
– Command syntax: input arguments always
interpreted as strings
– Functions syntax: input argument interpreted as
is and according to what the function expects

6
The journey continues ...

 Recap of Syntax Basics


 Program Design and Development
• Program Control Statements

7
Program Design and Development
• Plan the Program, start with Pseudo-Code

• Select the Right Data Structures

• Employ efficient Coding Practices

• Use comments generously

• Develop and Code in Steps

• Test and Debug your Program


8
Program Design and Development
• An algorithm
– is the sequence of steps needed to solve a problem
• A computer Program
– A group of statements to achieve an algorithm
• Create your program in a text editor preferably
using the MATLAB editor/Debugger
• Save your code with the .m file extension

9
Types of Program Files
MATLAB scripts:
• simply execute a series of MATLAB Statements
• Are useful for automating a series of steps you
need to perform many times.
• Do not accept input arguments or return output
arguments.
• Store variables in a workspace that is shared with
other scripts and with the MATLAB command line
interface.

10
Types of Program Files
MATLAB functions:
• Are useful for extending the MATLAB language for
your application
• Can accept input arguments and produce output
• Store variables in a workspace internal to the
function

11
Program Design and Development
• Sometimes we need to selectively execute
certain portions of our code
• Sometimes we need to repeat sections of the
program more than once
• Control statements: branches and loops
• Top-Down Approach of Program Design
• think out a problem and the solving approach
before writing a single line of code – it pays!

12
Scientific Problem Solving
• State the problem
• Describe the input values (knowns) and the
required outputs (unknowns).
• Develop an algorithm to solve the problem
– Top-Down Approach of Program Design
• Solve the problem
– create the MATLAB solution
• Test the solution

13
Program Design
and Development

14
Top-Down Approach of Program Design
• In the algorithm development stage of
program design
• Look for logical subdivisions and create
subtasks
• Decompose further into simple, clearly
understandable job
• Stepwise refinement of each piece
– Using pseudocode
– Hand-solving the problem can aid here
15
Agenda ...

 Recap of Syntax Basics


 Program Design and Development
 Program Control Statements

16
Program Control Statements

17
Recap of relational and logical operators
• Relational
• < > == ~=
• =< =>
• Logical
• AND: &, &&
• OR: |, ||
• NOT: ~
• XOR: xor

18
Quick Look
Assume that a, b, c, and d are defined:

What is the result of:


• ~(a > b) • logical(d)
• a > c && b > c •a * b > c
• c <= d • a * (b > c)

19
Program Control – IF construct
% The simple if-syntax % The if-else syntax
if <condition> if <condition>
... <statements 1>
<statements> else
... <statements 2>
end end
<condition> can be any MATLAB relational and/or
logical expression – any expression that
returns a logical value
<statements> can be made up of any valid MATLAB
expression

20
Program Control – IF construct
% example 1 % example 2
if rand > 0.5 if rand > 0.5
disp(‘Great’) disp(’A Head’)
end else
disp(‘A Tail’)
end

<condition> can be any MATLAB logical expression


– any expression that returns a logical
value
<statements> can be made up of any valid MATLAB
expression
21
Program Control – IF construct
% if-elseif syntax % example 3
Age1 = input(‘Your age: ’)
if <condition 1>
if Age1 < 18
<statements 1> disp(’You’’re too young’)
elseif Age1 >= 18 && Age1 <= 40
elseif <condition 1>
disp(’You’’re Welcome’)
<statements 1> elseif Age1 > 40
disp(’You’’re too old’)
end end

<condition> can be any MATLAB logical expression – any


expression that returns a logical value
<statements> can be made up of any valid MATLAB expression
NB: only the statements of the first true condition are
executed
22
Program Control – IF construct
% multiple if-elseif clauses
% Nested ifs
if <condition 1>
if <condition 1> ...
<statements 1> elseif <condition 2>
if <condition 2> ...
<statements 2> elseif <condition 3>
end ...
<statements ctd> elseif <condition n>
end ...
else % optional else
% The last end is <otherwise statement>
associated with the end
most recent if % only the statements of the
% Indent for readability first true condition are
executed 23
Your turn
• The following statements are intended to alert a user to
dangerously high oral thermometer readings (values are in
degrees Fahrenheit). Are they correct or incorrect? If they are
incorrect, explain why and correct them.

24
One more
• Write a program to calculate the roots of a
quadratic equation regardless of type.
• The program is to accept the coefficients of
the expression, tell the type of roots and then
display the results
• Hint 1: use the almighty formula for solving
• Hint 2: use the discriminant for type of root

25
Program Control – SWITCH construct
• another form of branching construct

• Test for equality against a set of known values

• select a particular code block to execute based


on the value of the switch expression
• Only Statements corresponding to the first true
condition are executed

26
SWITCH construct syntax

27
Program Control – SWITCH construct

28
Error control – try-catch
• another form of branching % the general syntax is
construct try % try block
• Used to trap errors <Statements
• Error in the try block causes to try>
execution of the catch block Catch % Catch Block
<Statements
to execute if
error
in the try block>
end

29
Error control example

30
Program Control Statements

31
Loop Control
(Repetition Structures)
• Loops permit the repetitive execution of a
block of code
• Two basic forms: for loop and while loop
• Counted loop – repeat specific number of
times, – the FOR loops
• Conditional loop – repeat until condition is
false – the WHILE loops
• Loops sometimes not necessary –
vectorising would be more efficient
32
Loop control – FOR loop
• repeatedly execute a block of code a specific number
of times,
• keeping track of each iteration with an incrementing
index variable
• Used when the number of repetitions is known
before hand
% the general syntax is
for index = start:increment:end
statements
end
33
FOR loop - examples
% simple loop 1
for k = 1:5, disp(k), end

% simple loop 2
x = ones(1,10);
for n = 3:2:10,
x(n) = 2 * x(n - 2);
end
34
FOR loop - examples
% find the no. of test scores
% above 90 per cent
scores = [76,92,45,98,80,97,90,67];
count = 0;
for k=1:length(scores)
if scores(k)>90
count = count + 1;
end
end
disp(count)

35
Your turn 1
• Generate a 10-by-3-by-5 array
representing RGB values for a 10x5 pixel
image.
• Reshape the array to a 10-by-5-by-3 array
containing the same information

DomEz Systems
36
Your turn 2
• Write MATLAB code to perform the Newton’s
method of finding square root
1.Initialize a
2.Initialize x to a/2
3.Repeat 6 times (say)
Replace x by (x + a/x)/2
Display x
4.Stop

• Compare with MATLAB’s sqrt function


37
Loop control – FOR Loop
Control with arrays
• The index variable takes on an entire column of the
array in each iteration – This is what actually happens
k = 1:5  k = [1,2,3,4,5]
• Similarly, in k = [3,5,7]
• Thus in k = [4,3,8;7,9,2]
k will take the values
 4  3 8 
k   k   k  
7  9  2
38
Loop control – While Loop
• Statements repeat as long as some condition
remains true
– loops continue until some criterion is met
– Or the specified condition becomes false
% the general syntax is
while expression
<statements>
end
% the expression produces a logical value

39
Loop control – While Loop
% simple example
k = 0; while k < 3, k = k+1, end

% find the first integer n for which


% factorial(n) is a 100-digit number:
n = 1;
nFactorial = 1;
while nFactorial < 1e100
n = n + 1;
nFactorial = nFactorial * n;
end
40
Your turn
1. Use a while loop to create a vector of the squares of
the numbers 1 through 5.
2. A store owner asks you to write a program for use in
the checkout process. The program should:
– Prompt the user to enter the cost of the fi rst item.
– Continue to prompt for additional items, until the user
enters 0.
– Display the total.
– Prompt for the dollar amount the customer submits as
payment.
– Display the change due.
41
Nested Loops
for ii = 1:3
for jj = 1:3
product = ii * jj;
fprintf('%d * %d = %d\n',ii,jj,product);
end
end

% NB1: an end statement is associated with the


% innermost currently open construct.
% NB2: The nested loops must have different index
% variables
42
Loop control – Break and Continue
• Break off from the smallest loop
• or skip to the next iteration
for ii = 1:5
if ii == 3;
for ii = 1:5
break;
if ii == 3;
end
continue;
fprintf('ii = %d\n',ii);
end
end
fprintf('ii = %d\n',ii);
disp(['End of loop!']);
end
disp(['End of loop!']);

43
Loop control – Break and Continue

44
Loop control
Good programming practices
• Indent the bodies of loops for clarity
and readability
• Comment generously
• Don’t modify the loop index within
the body of the loop
• Preallocate arrays
• Vectorise your code

45
Vectorisation of Code
• Avoid loops as much as possible
• convert loops into vectorised codes
– Directly OR Using logical arrays and operators

A = ones(200);
% instead of
for k = 1:length(A(:))
B(k) = A(k)*pi;
end

% use
B = A*pi;
46
Vectorisation of Code
• Logical arrays can serve as a mask for arithmetic operations
% for instance to take the square root of all
% elements in an array whose value is greater than 5
for ii = 1:size(a,1)
for jj = 1:size(a,2)
if a(ii,jj) > 5
a(ii,jj) = sqrt(a(ii,jj));
end
end b = a > 5;
end a(b) = sqrt(a(b));
• … vectorised approach is more compact and elegant than the
loop approach.

47
Program control statements
 IF construct
SWITCH construct
TRY construct
FOR loop
WHILE loop
Vectorisation of code
48
We’ve come thus far ...

 Recap of Syntax Basics


 Program Design and Development
 Program Control Statements
Exercises

49
Ex. 1 – cost vs. weight
• The cost of sending a package by an express delivery
service is $15.00 for the first two pounds, and $5.00
for each pound or fraction thereof over two pounds.
If the package weighs more than 70 pounds, a
$15.00 excess weight surcharge is added to the cost.
No package over 100 pounds will be accepted.
• Write a program that accepts the weight of a
package in pounds and computes the cost of mailing
the package. Be sure to handle the case of
overweight packages.

50
Ex. 2 – cost vs. distance
• The cost per mile for a rented vehicle is $1.00
for the first 100 miles, $0.80 for the next 200
miles, and $0.70 for all miles in excess of 300
miles.
• Write MATLAB statements that determine the
total cost and the average cost per mile for a
given number of miles (stored in variable
distance).

51
Ex. 3 - Calculating the Day of Year
• The day of year is the number of days (including the current
day) that have elapsed since the beginning of a given year. It is
a number in the range 1 to 365 for ordinary years, and 1 to 366
for leap years.
• Write a MATLAB program that accepts a day, month, and year,
and calculates the day of year corresponding to that date.
• The program should that the input data is valid and if invalid, it
should the user what is wrong.
• The year should be a number greater than zero, the month
should be a number between 1 and 12, and the day should be
a number between 1 and a maximum that depends on the
month. Use a switch construct to implement the bounds
checking performed on the day.
52
Ex. 4 – Alternating Harmonic Series
• One of the popular numerical methods is the Alternating Harmonic Series
which converges to In(2). The series is evaluated as:

• But how far out do you have to take the series to get a good approximation
of In(2)?
• Write a MATLAB program, using while loop to solve this
problem. The convergence criterion is once the values vary by
less than 0.001. Once the convergence criterion is met, the
program should
1. output The value of the truncated series, and the number of terms taken to
converge.
2. Plot the cumulative sum of the series elements, up to the point where the
convergence criterion is met.
53
Ex. 5 – Sudoku Puzzle
• Write a program to randomly generate a 9x9
matrix of numbers between 1 and 9 obeying
the rules of the popular Sudoku game
• The program should Randomly set 54 entries to
zero with a minimum of 5 zeros in each
column, each row, and in each 3x3 submatrix
• With the program generate one and play
yourself
• Generate another and give a friend to play.
54
Ex. 6 – Bacterial Growth
• Suppose that a biologist performs an experiment in which he
or she measures the rate at which a specific type of bacterium
reproduces asexually in different culture media.
• The experiment shows that in Medium A the bacteria
reproduce once every 60 minutes, and in Medium B the
bacteria reproduce once every 90 minutes. Assume that a
single bacterium is placed on each culture medium at the
beginning of the experiment.
• Write a program that calculates and plots the number of
bacteria present in each culture at intervals of three hours
from the beginning of the experiment until 24 hours have
elapsed. Make two plots, one a linear xy plot and the other a
linear-log (semilogy) plot. How do the numbers of bacteria
compare on the two media after 24 hours?
55

You might also like