Week 4 session A lecture slides File

Computer
Programming
Chapter 4 Lab A:
Program Development and
Testing
Module overview










Chapter 1: Introduction to computer programming
and MatLab
Chapter 2: Control structures
Chapter 3: Functions
Chapter 4: Program development and testing
Chapter 5: Data types
Chapter 6: File input/output
Chapter 7: Program design
Chapter 8: Visualisation
Chapter 9: Code efficiency
Chapter 10: Images and image processing
Lecture objectives

After today’s lecture you should be able to:
 Incrementally
develop a MatLab function or program
 Test each stage of the incrementally developing
function or program
 Identify common types of error that can occur in
MatLab functions and scripts
 Debug and fix errors in scripts and functions
 Use MatLab's built-in error handling functions to help
in program debugging
Errors and debugging

Have already seen how editor gives
indications about possible errors and
warnings
Errors and debugging
There are different types of errors
 Syntax Error: Where what we type in
breaks the rules on how the language
should be written

In this example, if we want to write a multiplication, then we must
use the star operator *
Errors and debugging
There are different types of errors
 Run-time Error: Harder to spot, syntax is
ok. We hit an error when the code is run
 In the previous example, we can fix the
syntax error by writing

r = b * b – 4 * ac;

The editor will not show a syntax error (no
red) but the code will fail at run-time. Why?
Errors and debugging
Original line
r = b * b –
 Code after attempted fix

4 ac;
clear
a = input( 'Enter a: ' );
b = input( 'Enter b: ' );
c = input( 'Enter c: ' );
r = b * b – 4 * ac;
x1 = (-b+sqrt(r))/(2*a)
x2 = (-b-sqrt(r))/(2*a)

The editor will not show a syntax error (no
red) but the code will fail at run-time. Why?
Errors and debugging
There are different types of errors
 Run-time Error: Previous code referred to
a variable 'ac' which was not defined
 Can fix as follows

% ....
r = b * b – 4 * ac;
% ....
% ....
r = b * b – 4 * a * c;
% ....
Errors and debugging
There are different types of errors
 Logic Error: These are hardest to find
 Syntax is ok
 No error when the code is run
 But does not give correct results

Errors and debugging
There are different types of errors
At command line
 Logic Error:

function m = meanValue(x, y)
m = x + y / 2;
>>
>> a = 3; b = 4;
>> c = meanValue(a,b)
c =
end
5
In file meanValue.m
Logic error often due to
incorrect implementation of a
formula or algorithm
>>
In this example, the coder
has forgotten about
operator precedence
Errors - Recap
Three broad categories of error
 Syntax error
 Rules
for writing the language are broken
 Code cannot be executed

Run-time error
 No
syntax errors but code breaks down when it is
executed

Logic error
 No
syntax errors, No error at run time
 Code still behaves incorrectly, gives wrong
results
Validating input arguments


When we write a function, we expect particular
kinds of data for the arguments
Example: we have a function to estimate the
expected weight for a baby whose age is given
in months
function W = expectedWeight(ageInMonths)
% Usage:
• Use error when what the input
% ... usage text goes here ...
given makes it impossible to
proceed.
if (ageInMonths < 0)
error('Age cannot be negative') • Call to error: Give message
and exit immediately
end
% ... rest of function continues below ...
Validating input arguments

Function to estimate the expected weight for a
baby whose age is given in months
function W = expectedWeight(ageInMonths)
% Usage:
• Use warning when we can
% ... usage text goes here ...
proceed with the input but
results may be unreliable
if (ageInMonths > 60)
• With call to warning, message
warning('Really a baby??!')
is reported and function
end
continues
% ... rest of function continues below ...
Incremental Development

When writing a program to
 solve
a problem
 model a system, etc...

Adopt following steps for reliable code with fewer
errors
1.
2.
3.
4.
5.
Start with small amount of code
Test to make sure code behaves as expected
Add a small amount of code
Test again
Repeat steps 3 and 4 until completion
Incremental Development

The aim
 Always
have a working version of the program
 Even if it doesn't yet do everything we want it to do

Avoid trying to write everything in one go
 'big
bang'
Test repeatedly and often
 Iterate

Example in manual

The manual has an illustration of
incremental development to generate a
program
 Example
to calculate interest
 Sections 4.2 and 4.3
 Simple example, used to illustrate a way of
working

In this lab we will try to follow the same
way of working to generate a new program
for a different example
The Karvonen method for heart rate
calculation
Description: To get the maximum benefit from exercise, a person's
heart rate should be close to a target value and this will vary for
different people. It depends on the person's age and general fitness.
The Karvonen method of calculating the target heart rate (THR) is
popular and uses the person's resting heart rate (RHR) and their
maximum heart rate (MHR). The RHR gives an indication of the
general fitness and the MHR can be estimated by subtracting the
person's age from 220. The difference between the maximum and
resting heart rates is known as the reserve (RES). The THR is then
defined by a pair of limits. The lower limit for the THR is given as the
RHR plus 60% of the reserve. The upper limit is defined as the RHR
plus 80% of the reserve. The THR itself is half way between the limits
calculated. The person should aim for this value and their heart rate
during exercise should stay between the upper and lower limits.
Exercise


Write a program giving a user heart rate advice
based on the Karvonen method
The program should take in the person's age
and three measurements of their resting heart
rate taken on successive days
 The
overall RHR is estimated by taking the mean of
the three values.

The program should validate the user input and
give a report to the screen
 confirming
the user's data
 giving advice on their target heart rate and its limits
Tips for avoiding and tracking
errors
Validating input
 Stepping through the program with the
debugging tool
 Checking the values of variables as we
step through line by line

Tips in general
Use the increment/test approach
 Always seek to have working code
 Many small functions are better than one

huge function
Tips in general


You can use a second script or function that
calls your main program and test it
The early versions can be non-interactive
working with fixed data values
 passed
in as arguments
 or 'hard coded' in the main function


The results for these can be pre-calculated
and checked for correctness at each test.
The later versions can then introduce
interaction
Exercises
Go through section 4.5 of manual which
lists very common MatLab specific errors
 E.g:

 Matrix
shape issues
 Matrix vs element-wise operations
 Errors relating to the path

Now work through exercises 1-3 in the
manual at the end of chapter 4
Summary


We have considered how it is possible to improve the
process of writing code that is more reliable and with
fewer errors
Improvements can be achieved by




Incremental development
Frequent testing
Debugging
Validating input to functions carefully
Further resources

MatLab documentation on Programming
scripts and functions



Browse the subsections
Coding and Productivity Tips
Good MatLab coding style article at
http://www.datatool.com/downloads/matlab_style_guidelines.pdf
Any questions?