MATH1606 Programming With Matlab
MATH1606 Programming With Matlab
METHODS
Dr J P Hughes
These are the lecture notes for the Programming with Matlab part of the MATH1606
module.
Note that the lecture notes provide a summary of the main ideas in the module, but
they are not a substitute for attending lectures and tutorials! In fact there are gaps in
these notes which you will need to complete as we work through the material in the
lectures.
We shall use Matlab to create computer programs, which is an important skill for a
mathematics student. You will find that these programming skills will be used in
many of your other modules, in all years of your course here. For each section of the
notes, there are tutorial questions and it is very important that you work through all of
these questions, producing and running the necessary programs. You should work
through these in the computer practical sessions and complete them in your own
time when necessary.
A program is an ordered list of instructions which a computer can obey to carry out
some specified task. Complex programs will consist of many sub-programs, each of
which may have been written and thoroughly tested (hopefully!) by a different person
(or team) to do a specific sub-task. For some programming languages, there are
libraries of procedures which are available for some of the most commonly required
calculations.
In this section of the course we will learn how to write programs in the Matlab
programming language. These skills will be useful later on this module, when we
study numerical methods, in other modules and possibly in your future career.
On a University Windows Network PC, click on the Start button in the taskbar, point
to All Programs, University Software, Software M to O, M, MATLAB R2015A,
MATLAB R2015A.
Below is a screenshot of how the Matlab window may appear when you first open the
software. The exact appearance of the Matlab window will depend on the
configuration left by the previous user. Commands can be entered directly into the
Command Window after the >> symbol, which is called the Command Window
Prompt.
1
For example, type the following lines of code directly after the Command Window
Prompt, pressing the <Enter> key after each line. (Note that to assign a value to a
variable, we simply use the = sign in Matlab)
a=321;
b=654;
c=a+b;
disp(c)
The result 975 should appear in the Command Window. This short set of commands
simply sets a to the value 321, b to the value 654 and c to the value a+b (i.e. 975).
Finally the disp command will display this c value. The semi-colon ; at the end of
each line prevents the result of the command appearing as output when it is entered.
Try removing one of the semi-colons to see what happens.
Now type
clc
and press the <Enter> key to clear the contents of the command window.
Since we shall be using Matlab for programming, we will be writing all commands in
Matlab programs, or Scripts ( .m files). All of the commands in the program are
first entered, before running them, with the output appearing in the Command
Window. Matlab programs can also request user input from the Command Window.
2
Firstly, we can remove the Workspace and Command History windows by clicking
on the arrows at the top right corner of each, and selecting Close.
If you wish to restore the view of the Workspace and Command History windows,
then select Layout, and then choose to SHOW these windows.
It is useful to have the command window filling the right hand half of the screen, so
point at the central window divider and drag it to the halfway point.
We will now create our first Matlab program as a Script (.m file).
3
Firstly, click on the New Script button (or select New, then Script) and an Editor
window will appear.
Now resize and drag the Editor window so that it fills the left hand side of the window
(alongside the Command Window), as shown above. It is useful to have the Editor
and Command Window alongside each other, since the results of the program
created in the Editor will appear in the Command Window.
4
Now set the current directory to the location where you wish to save your work, e.g.
U:\Math1606\Matlab, by clicking on the Browse for folder button and selecting the
appropriate location. Note that if the Editor window disappears when you are doing
this, then it can be re-instated by clicking on its tab on the taskbar at the bottom of
the screen.
Now click on the Save button in the Editor window, followed by Save As. Enter a
suitable name (e.g. first) and click on Save. Matlab will automatically append .m onto
your filename to show that it is a Matlab Script file. This file will now be stored in your
chosen folder.
Matlab filenames
Matlab filenames must start with a letter (a to z) and may then contain any
combinations of letters and numbers. The only other allowable character is the
underscore _ which can be used to separate words (e.g. first_program).
5
1.3 First Matlab program
We shall now create our first simple program by typing it into the open Editor window.
Press the <Enter> key at the end of each line and remember to include the semi-
colons at the end of each line, which prevent the result of each command appearing
in the Command Window.
a=321;
b=654;
c=a+b;
disp(‘The sum is ’)
disp(c)
To run the program either click on the Run button or simply press F5 on your
keyboard. The output from running the program will appear in the Command
Window, and you should obtain
>> first
The sum is
975
The name of the program (first) is displayed, followed by the results/output generated
by the program. Alternatively, the program can also be run by typing the program
name (e.g. first) at the >> prompt in the Command Window.
Note that when you run the program from the Editor window (Run button or F5) then
it will be automatically saved, so if you have not already given it a name you will be
prompted to do so.
6
If the folder path where the current file in the Editor window is located is not the same
as the current directory, then you will obtain a message similar to the one below.
Selecting Change Folder will change the current directory to that of the file in the
Editor window. Alternatively, selecting Add to Path will add the folder path of the file
in the Editor window to the current directory. Either route should enable your
program to run.
Note that the result will only appear if the program does not contain any errors. To
see what happens if an error is present, delete the + symbol on line 3 of the code and
run the program. A red error message should appear in the Command Window, as
shown below, and the line of the error will be shown in this message.
Correct the error, by retyping the + symbol and run again. The correct result of 975
should now be obtained.
Try running the program a few times with different input values.
Note that the results from successive program runs will appear in the Command
Window. If you wish to remove this information, you can right mouse click in the
command window and select Clear Command Window. Alternatively typing clc in
the Command Window will clear its contents.
7
If you want to clear the command window before each new run, add the command
clc to the top line of your program. Hence, for the first program we have
clc
a=321;
b=654;
c=a+b;
disp(‘The sum is ’)
disp(c)
Note that we only need semi-colons after statements which include an = symbol,
since these lines of code are storing results in the variables to the left of the =
symbol.
The workspace
Each time you run a Matlab program, the content of each variable is stored in a
Workspace. To see the Workspace, select Layout, and then choose to SHOW the
Workspace. The following window will appear and the values of the a, b and c
variables can be seen in the Workspace.
It is a good idea to clear these values before you run the program again, or run a
different program. To clear the values you can right mouse click in the Workspace
and select Clear Workspace.
A simpler way, however, is to add the command clear at the beginning of each
program.
8
1.4 The structure of simple Matlab programs
Most Matlab programs that we meet in the early stages of learning to create
programs will involve 3 specific sequential stages.
In this stage, information is assigned to variables within the program. This may take
the form of an assignment statement, or an input statement that requests user input
from the keyboard. We shall consider different types of input statements later on.
a = b + c;
Here, the program will calculate the result on the right hand side of the equals sign
and store the result in the variable on the left hand side.
Once the calculations have been performed, the final stage in the program is usually
to output the results in the Command Window. Matlab has a number of different
ways of displaying results, which we will consider in more detail later.
The following program consists of these three stages. Firstly it requests input from
the program user as the program runs, reading in two numbers. Then, it evaluates
the sum and product of these numbers and finally it prints out the results.
sumandprod.m
% VARIABLES
% a - the first number
% b - the second number
% sum - the sum of the two numbers
% prod - the product of the two numbers
clear
clc
9
disp('Give 2 numbers on successive lines')
disp('Press the enter key after entering each number')
sum = a+b;
prod = a*b;
Any text following the percentage character % is a comment. This means Matlab
ignores everything else following the % character on that line. Comments are an
essential part of programming. You should always include a good number of
comments to let the reader know what your program is doing at all stages. In
particular, you should always say precisely what each variable in your program
represents. This provides a useful reminder to yourself when you refer back to a
program after some time. Marks will be lost in assessments if you do not do this!
When this program is run, it asks you to enter numbers into the Command Window.
You simply need to press <Enter> after each value. As you enter the values, the
Editor window will be minimised (and appear to vanish). To re-instate this window,
once the results have appeared in the Command Window, simply click on the tab on
the bottom taskbar, as described earlier.
Sample output obtained in the Command Window, from running this program is
The sum is
975
The product is
209934
Notice the positioning of the numeric output. Later, we shall meet commands that
give us better control of the formatting and positioning of output from programs.
10
Analysing the program structure
The first few lines are simply comments which outline what the program is doing and
what the variables used represent. This is good programming practice since it
provides useful information for someone else reading your program.
% VARIABLES
% a - the first number
% b - the second number
% sum - the sum of the two numbers
% prod - the product of the two numbers
The next part of the program is clearing the command window and clearing any
variables currently stored in the Workspace. It is good practice to clear any values
assigned to variables before running a program.
clear
clc
The next part of the program is the input section. The disp(….) statement is used
for displaying information in the Command Window, with the text that is to be
displayed inside single quotation marks ''. Two values are entered from the
keyboard, the first being stored in the variable a and the second in the variable b.
The input('a = ') statement is used to read the input, setting it equal to the
variables, and also print a message in the Command Window.
Then we have the calculation statements, which calculate the sum and product of
the variables a and b, storing these to the variables sum and prod.
sum = a+b;
prod = a*b;
11
Finally we have the output statements, which display the results in the Command
Window. The statement disp(' ') simply outputs a blank line, which is useful to
separate the input from the output.
1.5 Variables
Variables are simply memory locations which are used by the program to store
individual values. The term variable is used since these items may vary as the
program runs. Variable names in Matlab must satisfy the following requirements;-
1. the name must use only alphabetical (e.g. a-z, in lower or upper case) or
numerical characters (0-9).
3. the only special character that is allowed is the underscore _ which can be
used to separate words. Spaces and other special characters (e.g. +, *, &,
#) are not allowed in Matlab.
Note that Matlab is case sensitive, which means upper case letters are different to
lower case letters. It is usual practice to use lower case letters for variables.
If a result is calculated or inputted as an integer then Matlab will display it in this way
when using the disp( ) statement. In other cases, Matlab will display the number as
a decimal. If the number is large then scientific notation will be used.
Inside procedures, it is very common to want to use extra variables, which are not
input or output variables, in order to simplify the coding. For example, suppose we
wish to create a program which needs to calculate the following expression.
f
cos 1 1 x 2 sin 1 1 x 2
1 1 x2
12
Clearly we would wish to avoid writing 1 1 x 2 three times, so the following lines
of code would seem appropriate.
a=1+sqrt(1+x^2)
f=(cos(a)+sin(a))/a
This avoids the need for lengthy expressions, with many pairs of brackets, which are
not easy to read and can be prone to typing errors.
1.6 Operators
Matlab uses the usual BIDMAS mathematical law for order of precedence for these
operators;-
1. Brackets
2. Indices
Always use the precedence of operators where possible in order to reduce the
number of brackets used. Complicated expressions with many brackets are often
difficult to read, and it is then easy to have the brackets in the wrong place.
13
1.7 Mathematical functions in Matlab
Matlab has all of the usual mathematical functions available. The table below
summarises the most commonly used
Matlab has other special functions. Information on these can be obtained from the
Matlab help facility.
14
1.8 User Input
In the example sumandprod.m, the program asks the user to enter two numbers at
the Command Window Prompt. The coding used for this was
a = input('a = ');
b = input('b = ');
The sum is
975
The product is
209934
Notice that the text within the input command then appears at the Command Window
Prompt preceding the point at which the user inputs the values. If we do not wish to
have any text preceding the user input, then we use the coding
a = input('');
b = input('');
The sum is
975
The product is
209934
15
Rather than using the disp commands, and then the input command, the input stage
could be done more simply, as
The sum is
975
The product is
209934
However, although the coding is more straightforward in this second case, we do not
have the useful summary of variables and values displayed in the Command Window,
that we did in the first case.
So far we have used the disp(variable) statement to output results to the Command
Window. In this section we shall show the flexibility of this statement to output more
than one item on the same line. However, it is noted that the disp statement does
have its limitations with controlling formatting of output, and generally we shall use
the fprintf statement, which is described in the next sub-section.
c=1.456;
disp('c =')
disp(c)
c =
1.4560
16
We can use the disp statement to output more than one item on the same line. For
example, suppose we have three variables a, b and c, the statement
disp([a b c])
Note the use of the square brackets. The content of the square brackets can either
be all variables or all strings (text). A combination of the two is not allowed. To
combine strings and variables on the same line, we must use the num2str command.
num2str(variable) will convert the number to a string.
Modifying our first program, so that the disp statement is used to output the result on
one line we have
a=321;
b=654;
c=a+b;
disp(['The sum is ' num2str(c)])
The disp( ) statement can be used for simple output in a Matlab program, but it is
rather limited. For example, the number of decimal places that appear in the output
cannot be controlled using the disp( ) statement.
For full control of the output, we should use the fprintf command. This command
allows us to easily control the output and make it appear in exactly the form that we
require. We can also easily combine text and numerical values on the same line,
without having to use the num2str command to convert a number to a string.
a=1.234;
b=567;
fprintf('a =%8.5f b =%4.0f',a,b)
a = 1.23400 b = 567
17
The value of a is outputted to 5 decimal places and occupies 8 columns in total,
including 1 space before the value.
The value of b occupies 4 columns in total, with no decimal places including 1 space
before the value.
Single quotation marks, ' ', are used within the fprintf statement to start and finish
the output.
Each format starts with the % sign and the number of formats within the command
should match the number of variables to be printed out. The 1st format corresponds
to the 1st variable after the content within the single quotation marks (''), the 2nd
format corresponds to the 2nd variable, etc.
Note that the decimal point occupies one column. Minus signs also occupy one
column.
In these examples there was one space between the = sign and the value. However,
if the number occupies more digits than the number of columns, then the value is
outputted without any spaces preceding it. For example, if we were outputting the
value 23.45 using the format %1.4f, we would get 23.4500 with no spaces preceding
it. The use of 1 for the number of columns is very common, since the output simply
follows the previous text without any spaces.
(i) a=1.234;
b=-567;
fprintf('a=%6.2f b=%7.1f',a,b)
a = 1.23 b = -567.0
Note that the first value occupies 6 columns in total and the second value occupies 7
columns in total.
18
(ii) a=123.456;
b=-1.234;
c=4321.8765
fprintf('a =%7.3f b =%6.1f c =%5.0f',a,b,c)
(iii) a=-54.321;
b=12;
fprintf('a =%1.4f b =%6.0f',a,b)
a =-54.3210 b = 12
The first value contains more digits than the specified number of columns in the
format, 1. The value is then outputted without any preceding spaces. The second
value occupies 6 columns in total.
Note that fprintf can also be used to output a blank line, as follows
fprintf('\n')
If you want a number of blank lines, you can simply include \n as many times as you
wish. For example to output 3 blank lines
fprintf('\n\n\n')
19
The \n command may be used to output values on successive lines, using only one
fprintf command. For example
a=1.23;
b=4;
fprintf('a =%4.1f\nb =%4.1f',a,b);
would output the values of a and b to 1 decimal place on successive lines, as shown
below.
a = 1.2
b = 4.0
We could also use the Matlab integer format as an alternative to %5.0f. We could
simply use %5i instead, which would output the value, right justified, in 5 columns.
a=5;
b=67;
fprintf('a =%4i b =%3i',a,b)
a = 5 b = 67
20
Programming Tutorial 1
For exercise questions that you need to submit for assessment, you will need to
submit your Matlab program contained in the Editor window (.m file), and also the
output obtained when running the program for the test cases. Therefore, once you
have got your program working correctly, you should copy and paste both the
program and the Command Window output into a Word document. Once in Word,
you may wish to change the font and font size. In these notes the Matlab program
and output is presented in Courier New font, bold, size 12. At the end of this tutorial
section is an example of doing this for the sumandprod.m program.
Exercise 1.
Write a program in which the user is asked to input x and y, the coordinates of a point
in the plane, and then the program evaluates the distance of that point from the
coordinate origin. Don't forget to include suitable comments and an appropriate print
statement. Test your procedure and then find the distance of the point (2.3,4.5) from
the origin.
Exercise 2.
A cylindrical water storage tank has a semi-spherical top, as shown in the diagram
below.
r
r
2 3
For a tank with cylinder height h and radius r, the volume is given by r 2h r
3
and the total surface area is given by 2 rh 3 r 2 . Write a program which asks the
user to input h and r and then the program evaluates the volume and total surface
area of the tank. The program should print out a summary including the radius and
height of the tank, as well as the calculated volume and surface area. Also, include
suitable comments in your program.
Use your program to determine the volume and total surface area of the following
circular cylinders;- (i) height = 3.4, radius = 1.2 and (ii) height = 1.53, radius = 2.21.
21
Exercise 3.
Write a program to calculate a person's weekly wage. The user should be asked to
input the number of hours worked, the normal hourly rate of pay and the overtime
hourly rate of pay. A normal working week is 40 hours and if an employee works less
than 40 hours, pay is deducted at the overtime rate. This may seem a little unfair but
it enables the calculation to be done in ONE simple command without the need to
test whether the number of hours worked is greater or less than 40 (using commands
we have not met yet). Include appropriate print statements to provide a summary of
the hours worked, the normal and overtime hourly rates and the person's weekly
wage. It is recommended to use more than one print statement in order to obtain an
easier to read summary on several lines. Your program should also include suitable
comments.
Run your program with £10.80 as the normal hourly rate of pay, £16.20 as the
overtime hourly rate and for 32, 40 and 48 hours.
Exercise 4.
A mortgage is an arrangement under which a person (the mortgagee) borrows a sum
of money, £A, from another person (the mortgager) against a security such as a
house. The mortgagee agrees to repay the money over a period of n years at a
current interest rate of r% per year. If the interest calculations and the repayments,
of £P, are made annually then,
n
r
A r 1
P 100
r
n
100 1 1
100
Write a program which asks the user to input A, n and r and then the program
calculates P. Include suitable comments and also appropriate print statements to
provide a summary of the amount borrowed, the interest rate, the repayment period
and the annual payment.
22
Sample presentation of solutions
% VARIABLES
% a - the first number
% b - the second number
% sum - the sum of the two numbers
% prod - the product of the two numbers
clear
clc
sum = a+b;
prod = a*b;
Output
The sum is
975
The product is
209934
23
24
2. Repetition in Matlab – loops
Suppose we wish to print the squares of the first n integers, i.e. 1,4,9,16,25,..., n 2 .
squares.m
% VARIABLES
% i - the counting (loop) variable
% n - an integer
% sq - square of the integer
clear
clc
n = 10;
for i=1:n
sq=i^2;
fprintf('%1i\n',sq)
end
25
Here, the value of n is set by editing the program. Note that when you start a for loop
in the Editor, Matlab will automatically indent the lines of code within the for loop.
This improves the readability of the program, making it easier to identify where loops
start and end, and is good programming practice.
The commands between for and end will be executed for each value of i. Hence the
numbers 12 to 10 2 will be displayed in the Command Window in a vertical column.
In the fprintf statement, %1i is used to output the numbers in integer format. As only
1 column is specified for the output, Matlab will automatically adjust the number of
columns for numbers with two or more digits. \n is used so that the output from
subsequent fprintf commands will be on a new line. Try removing the \n from the
fprintf statement within the for loop, and the numbers should now appear on the
same line.
The following procedure has three commands (print statements) within the do loop.
powers.m
% VARIABLES
% i - the counting (loop) variable
% n - an integer
clear
clc
n = 4;
for i=1:n
fprintf('%1i\n',i^2)
fprintf('%1i\n',i^3)
fprintf('%1i\n',i^4)
fprintf('\n')
end
26
The output would be
1
1
1
4
8
16
9
27
81
16
64
256
factn.m
% VARIABLES
% i - the counting (loop) variable
% n - the number for which the factorial value is to be
evaluated
% fact - the variable used to store the factorial value
clear
clc
27
disp('Enter a positive integer for which the factorial is
to be evaluated')
n = input('n = ');
disp(' ')
for i=1:n
fact=fact*i;
end
We can have greater control within a for loop than we have illustrated in the
examples so far. We can start counting at any number and increase by any step we
choose by using the more general form of a for loop in Matlab, which is
statement 1
statement 2
end
28
Here the instructions between for and end will be executed as;-
- i takes values from istart to iend
- in steps of istep
Note that we can use any valid Matlab name for the loop counter.
The values for istart, istep, iend can be any kind of number (integer and non-integer).
Many programming languages restrict loop values to integers (i.e. whole numbers),
but this is not the case in Matlab.
If istep is negative, the loop variable simply decreases at each pass through the loop,
and the loop terminates when its value is less than iend. For example, in the
following code
for p=6:-2:2
statement 1;
statement 2;
statement 3;
end
the loop would repeat its internal statements 3 times with p equal to 6, 4 and 2
respectively.
Note that if the end limit (iend) is less than the start limit (istart), and the increment
istep is positive, then the loop would not execute at all. Similarly if the increment
istep is negative and the start limit (istart) is less than the end limit (iend), then the
loop would also not execute.
The next example does exactly what its initial comment says it does.
sumsq.m
% VARIABLES
% i - the counting (loop) variable
% sum - the running total
clear
clc
29
% Initialising the sum
sum=0;
for i=100:2:200
sum=sum+i^2;
end
sumsqgen.m
% VARIABLES
% i - the counting (loop) variable
% int1 - the first even integer to be squared
% int2 - the second even integer to be squared
clear
clc
30
disp('Give a positive even integer for the upper limit')
int2 = input(' ');
disp(' ')
for i=int1:2:int2
sum=sum+i^2;
end
You can have one (or more) loop(s) of commands inside another. This is called
nesting the loops.
timestables.m
% VARIABLES
% i - counter for which table is being printed
% j - counter to do the multiplication
% t1 - the first times table to print
% t2 - the last times table to print
31
clear
clc
for i=t1:t2
fprintf('\n')
fprintf('This is the %1i times table\n',i)
fprintf('\n')
for j=1:3
fprintf('%1i times %1i is %1i\n',j,i,j*i)
end
end
32
This is the 1 times table
1 times 1 is 1
2 times 1 is 2
3 times 1 is 3
1 times 2 is 2
2 times 2 is 4
3 times 2 is 6
1 times 3 is 3
2 times 3 is 6
3 times 3 is 9
1 times 4 is 4
2 times 4 is 8
3 times 4 is 12
x2 x3
1 x
2! 3 !
The following program can be used to sum the first n terms of this series for a
particular value of x. In this program a nested loop is used to evaluate the factorial of
each term in the series.
expseries.m
% VARIABLES
% i,j - the counting (loop) variable
% n - the number of terms in the series
% x - the variable x
% fact - the variable used to store the factorial value
% sum - the running total
33
clear
clc
for i=1:n
for j=1:(i-1)
fact=fact*j;
end
end
34
As expseries.m runs, we have
35
2.2 While loops
In the previous section we used the for ... end construct which repeated instructions
until the final value of the loop counter was reached. Sometimes we will wish to stop
the loop when some condition is satisfied. In Matlab, conditional loops such as this
are called while loops.
The following program successively squares numbers until they exceed 1000.
squaresofsquares.m
% VARIABLES
% first - the first number to be squared
% current - the current number to be squared
clear
clc
current=first;
while current<1000
current=current^2;
fprintf('%1i\n',current);
end
36
Note that in this program, we name the input value from the user as first, and then
use current as the variable for the latest value. The program would have been
simpler, if we had overwritten the input value first on each iteration, but it is good
programming practice not to overwrite program input values.
16
256
65536
Notice that here, the loop continues whilst the value of current is less than 1000, and
this criteria is tested before each iteration of the loop. So on the third iteration, the
value of 65536 is printed since when the criteria was assessed at the start of this
iteration the value of current was less than 1000 (it was 256). Then at the beginning
of the fourth iteration, the value of current exceeds 1000 so the iterations are stopped.
Note that for this program, if the first number is 1, then the loop will continue
indefinitely as the value of current remains as 1. If the first number is less than 1,
then the loop also continues indefinitely as it approaches zero. In this case we can
interrupt Matlab by simultaneously pressing Ctrl and C on the keyboard. The
calculation should then stop, with the message " Operation terminated by user during
squaresofsquares (line 19)" displayed in the Command Window. In this program, it
would be useful to have greater control by setting an upper limit of iterations and then
stopping the iterations when the criteria is reached. We will consider this later in the
course.
while condition
statement 1
statement 2
end
Note that, as with a for loop, Matlab will automatically indent the lines of code within a
while loop, which improves the readability of the program.
37
The condition can be any statement which delivers the value true or false, as shown
in the following table.
If the condition is true, the statements within the loop are executed once. If the
condition is false the statements are not executed at all.
Once the statements have been executed, the condition is again tested and the
situation repeats until the condition is false.
38
Programming Tutorial 2
In order to keep a record of the Matlab programs that you create, and the output
generated for the test cases, I suggest you copy and paste both the program and the
Command Window output into a Word document, as described at the beginning of
programming tutorial 1.
Exercise 1.
Write a program which successively halves a number (>=1), entered by the program
user, until the result is less than 1.
The program should print out the first number, and then the value each time it is
successively halved.
Test your program with the first number as (i) 10 , (ii) 16.
Exercise 2.
Write a program which find the sum of the first n terms of:
(i) 1 3 5 7
(ii) 1 2x 3x 2 4x 3
x 5 x 7 x 9 x 11
(iii)
5 7 9 11
Note that you need to produce a different program for each series.
The program for series (i) should ask the user for one input value, n.
The program for series (ii) and (iii) should ask the user for two input values, n and x.
The output of the program should include a summary of the number of terms, the
value of x (where appropriate) and the sum of the series.
Test all of your procedures with n 5 and in series (ii) and (iii) x 1.6 .
Exercise 3.
The function cos x can be approximated (using a Maclaurin expansion) by the
series
x2 x4 x6
1
2! 4! 6!
Write a program which finds the sum of the first n terms of this series for a particular
value of x. The factorials should be evaluated within your program, as demonstrated
in the lecture examples.
Use your procedure with n 2, 4, 6, 8 and x 1.2 to confirm that as more terms of
the series are included, then the sum of the series does converge to the correct value.
39
40
3. Making decisions in Matlab – if statements
3.1 If statements
if condition
statement 1
statement 2
end
Note that the if statement terminates with end. In this case the statements are
performed if the condition is true. The statements are not performed if the condition
is false.
Also, note that when you start an if statement in the Editor, Matlab will automatically
indent the lines of code within the if statement, which improves the readability of the
program.
The condition is often a test for equality or inequality for which the following
(relational) operators are used in Matlab:
41
Sometimes we want to use a condition which is dependent on two (or more)
individual conditions. Matlab has the (logical) operators and, which is written as &&
in Matlab, and or, which is written as || (i.e. shift \ on the keyboard) in Matlab. Simple
examples of these are;-
cond1 && cond2 - both conditions cond1 and cond2 must be true for the result to
be true
cond1 || cond2 - at least one of the conditions cond1 and cond2 must be true
for the result to be true
greet1.m
% VARIABLES
% time - the time of day
clear
clc
Notice that in this code, rather than using a disp statement to ask the user for input,
as we used in earlier examples, we have incorporated the necessary message into
the input statement. If the message is simple, it is sometimes better to do this.
Sample output is
Good morning!
or
Input the time (and press Enter): 14
Here, if the value of time is 12 or greater then the program does not return any
message.
42
3.1.2 The if … else … end statement
if condition
true statements
else
false statements
end
The true statements between if and else will be performed if the condition is true,
otherwise the false statements between else and end will be performed.
greet1.m
% VARIABLES
% time - the time of day
clear
clc
Sample output is
Good morning!
43
or
Input the time (and press Enter): 15
Good afternoon!
or
Input the time (and press Enter): 20
Good afternoon!
or
Input the time (and press Enter): 55
Good afternoon!
Obtaining "Good afternoon!" for times of 20 or 55 is not ideal. The next section
extends the possibilities.
if condition1
statements 1
elseif condition2
statements 2
else
statements 3
end
44
More elseif statements can be included if needed. Note that in some instances, we
may wish to omit the else part within an if-elseif statement.
greet3.m
% VARIABLES
% time - the time of day
clear
clc
Sample output is
Good morning!
or
Input the time (and press Enter): 14
Good afternoon!
or
Input the time (and press Enter): 20
Good evening!
45
or
Input the time (and press Enter): 23.5
Good night!
or
If, by error, the time is incorrectly entered as a negative value, then the current
program returns;-
Good afternoon!
We therefore modify our program to account for negative values being entered
mistakenly.
greet4.m
% VARIABLES
% time - the time of day
clear
clc
if time<0 || time>24
fprintf('Input time out of range for normal 24 hour
clock!\n')
elseif time<12
fprintf('Good morning!\n')
elseif time<18
fprintf('Good afternoon!\n')
elseif time<23
fprintf('Good evening!\n')
else
fprintf('Good night!\n')
end
46
Running this program, we obtain the following output
Time Output
-1 Input time out of range for normal 24 hour clock!
9 Good morning!
14 Good afternoon!
20 Good evening!
23.5 Good night!
25 Input time out of range for normal 24 hour clock!
cos x 0x
g x
e
x2 x0
First, we consider how the if ... end structure can be used to compute the function
g x , by looking at a possible program for this purpose.
g.m
% VARIABLES
% x - the variable x
% answer - the result
clear
clc
if x>0
answer=cos(x);
end
if x<=0
answer=exp(-x^2);
end
47
Sample output is
or
Enter the value of x: 0
or
Enter the value of x: 1
Let's run through the program, starting at the beginning. Matlab enters the procedure
with the given value of x. It then executes the first test, to find if x>0: if so answer is
given the value cos(x); if not, nothing happens. Matlab then executes the second
test to find if x<=0: if so answer is given the value exp(-x^2); if not, nothing happens.
So, for any (real) value of x, the variable answer is now assigned the correct function
value. Matlab then comes to the last line of code, and prints out the current value of
answer, namely the correct function value.
This program does what it was designed to do. But it has a defect of programming
style. The above construction is a bit clumsy as essentially the same test has been
performed twice to see whether x is positive or non-positive. To overcome this and
produce more elegant code, we should use an if … else … end statement. The
following program does this.
48
g0.m
% VARIABLES
% x - the variable x
% answer - the result
clear
clc
if x>0
answer=cos(x);
else
answer=exp(-x^2);
end
Here, we simply test if x is positive, and if it is not positive, then it must be non-
positive. The output produced by this program (g0.m) is identical to that for the
original version (g.m).
49
Suppose it is required to construct a program which returned the values of the
following function
e x x 1
1 x 1
v x 0 0 x 1
1 x0
e x x0
Although there are five separate ranges of x for this function, we can use the
symmetry of the function, and the Matlab logical operators and (&&) and or (||) to
simplify the coding. The following procedure uses both of these logical operators in
carrying out tests on the value of x.
v.m
% VARIABLES
% x - the variable x
% answer - the result
clear
clc
if x>1 || x<0
answer=exp(-x^2);
elseif x<1 && x>0;
answer=0;
else
answer=1;
end
Sample output is
50
or
Enter the value of x: 0
or
Enter the value of x: 0.5
or
Enter the value of x: 1
or
Enter the value of x: 2
Programming Tutorial 3
In order to keep a record of the Matlab programs that you create, and the output
generated for the test cases, I suggest you copy and paste both the program and the
Command Window output into a Word document, as described at the beginning of
programming tutorial 1.
Exercise 1.
The number of days in a month is given by the following rules, assuming it is not a
leap year.
If month number is 2 the number of days is 28.
If month number is 4, 6, 9 or 11 the number of days is 30.
If the month number is anything else the number of days is 31.
Note that the month numbers correspond to;- 1 = January through to
12 = December.
Write a program which asks the user to enter the month number and then the
program prints out the month number and the number of days in that month. Your
program should do this as efficiently as possible. If an inappropriate month number
is entered, then a suitable message should be printed.
Also, create a modified version of your program, so that you can easily test the code
for each month of the year.
51
Exercise 2.
Write a program which calculates the area of a rectangle or a circle, depending on
the request of the user. It should have an initial input parameter, which decides
whether it is a rectangle (option 1) or a circle (option 2) for which the area is to be
calculated. If any other option value is entered, then the program should print a
suitable message, reminding the user of the correct option values. Depending on the
option entered, the program should then ask the user to input the relevant
parameters to calculate, and print out, the area of the selected shape.
Exercise 3.
Write a program which will find all 3-digit numbers which are equal to the sum of the
cubes of their digits, e.g. 153 13 5 3 3 3
Hints:-
There should be no input parameters for this program.
The three digit number can be split into hundreds, tens and units.
By using loops each three digit number can be formed and the sum of the cubes of
the digits can be evaluated.
The procedure should print all of the 3-digit numbers that meet the criteria.
52
4. Further programming techniques in Matlab
f x sin x cos x x2
In programming terms, x is the input parameter to this function and f is the output
parameter. In this case f is therefore a function of one variable.
function y = f(x)
y = sin(x)+cos(x)+x^2;
end
Type this code into a new Matlab Script (.m file) and save it as f.m. Note that the
variable y can be any valid Matlab name, as long as it is the same on the first line
and in the following definition.
Now make sure that the folder in which you saved the file f.m is added to the Matlab
path, using the Browse for folder button, as described on page 5 of these Matlab
notes.
To evaluate the function that we have just created, when x 2 , simply type f(2) at the
Command Window Prompt, >>. You should have the following in your command
window
>> f(2)
ans =
4.4932
53
In this case the function value f(2) has been calculated and the result has been
displayed in the command window. The value returned by the function is stored in
the default variable ans.
Note that a function such as f.m cannot be used simply by clicking on the Run button
(or pressing F5), as this does not define the input parameter required by the function.
If you try to run it, you should obtain the following output in the command window.
Once you have defined, and saved, the function f.m, it can be called from within other
Matlab programs. For example, the following Matlab program evaluates and displays
the function values for a range of x values.
fvalues.m
clear
clc
fprintf(' x f(x)\n')
for x=1:5
fprintf('%6.4f %7.4f\n',x,f(x))
end
The output is
x f(x)
1.0000 2.3818
2.0000 4.4932
3.0000 8.1511
4.0000 14.5896
5.0000 24.3247
So, it is possible to call a function from typing its name (and input parameter) at the
Command Window Prompt, >>, or from within another program.
If we now wish to produce a similar table of values for a different function, we do not
need to edit the main program, but simply edit the function defined in f.m and then re-
run the main program, fvalues.m.
We can also use the function defined in f.m within another program that has its own
input parameters. The following program has one input, a power, and then produces
a table of f x .
n
54
fpowers.m
function fpowers(n)
fprintf(' x (f(x))^%1i\n',n)
for x=1:5
fprintf('%6.4f %1.4f\n',x,(f(x))^n)
end
end
Note that we have not used the clear and clc commands within this program, as clear
would have cleared the input variable, n, before it is used and clc would clear the
display of the call to the function in the Command Window. If we need to use these
commands, then they can be issued in the Command Window before calling the
program.
Sample output is
>> fpowers(2)
x (f(x))^2
1.0000 5.6728
2.0000 20.1884
3.0000 66.4409
4.0000 212.8551
5.0000 591.6929
or
>> fpowers(3)
x (f(x))^3
1.0000 13.5114
2.0000 90.7095
3.0000 541.5681
4.0000 3105.4607
5.0000 14392.7741
55
4.1.2 Using a function definition at the bottom of the program
It also possible to define such a function at the bottom of a program in the following
manner
fvalues_in.m
function fvalues_in
clear
clc
fprintf(' x f(x)\n')
for x=1:5
fprintf('%6.4f %7.4f\n',x,f(x))
end
function y = f(x)
y = sin(x)+cos(x)+x^2;
end
end
The output obtained from running fvalues_in.m is exactly the same as the output
obtained from fvalues.m.
(i) If we are defining a function at the bottom of the program, then the first line of
the program must include a function heading. The name should be chosen
to be meaningful in the context of the program’s use, and ideally should be the
same as the Matlab Script (.m file) name. If you omit this first function line, the
program will not run (try it). Note that, although the term function is used, there
are no input or output parameters to fvalues_in.m
(ii) The function is simply written at the bottom of the program, and y can be any
valid Matlab name (i.e. it does not have to be y). Similarly x can be any valid
variable, as long as we use the same variable inside the bracket of the function
definition as used in the function itself. Also, we can use f(x) in the function call
and a different input parameter throughout the function definition. Hence, the
following code, would be perfectly suitable
56
function fvalues_in_2
clear
clc
fprintf(' x f(x)\n')
for x=1:5
fprintf('%6.4f %7.4f\n',x,f(x))
end
function a = f(t)
a = sin(t)+cos(t)+t^2;
end
end
(iii) We can have more than one user-defined function at the bottom of the program,
as long as we give them different function names, e.g. f, g, h etc.
The following is a function called calcarea, which calculates and returns the area of a
circle.
calcarea.m
% VARIABLES
% rad - radius of the circle (input)
% area - area of the circle (output)
area=pi*rad^2;
end
The radius of a circle is the input parameter, rad. The function then calculates the
area of this circle and stores it in the output parameter area.
Sample output is
calcarea(4)
ans =
50.2655
57
The value returned by the function is stored in the default variable ans. The result
returned from the function can also be stored in any other valid variable name, using
an assignment statement, perhaps for use in subsequent calculations. For example,
we can set the output from the function to a variable named myarea, as follows
myarea=calcarea(4)
myarea =
50.2655
In many cases, we will wish to create functions with more than one input parameter.
For example, the volume of a cone is given by
r 2h
V
3
where r is the radius of the circular base and h is the height of the cone.
conevol.m
% VARIABLES
% r - radius of the cone base (input)
% h - height of the cone (input)
% vol - volume of the cone (output)
vol=pi*r^2*h/3;
end
Sample output is
conevol(1.5,4)
ans =
9.4248
As the function has two input parameters, then two values must be entered
(separated by a comma) when it is called. The first value that is entered in the call is
stored in the first input parameter (in this case r) and the second value that is entered
in the call is stored in the second input parameter (in this case h). The order is very
58
important, as the parameters in the function call must correspond one-to-one with the
input parameters in the function definition.
We can create Matlab programs with input parameters, which are entered as we call
the program at the Command Window Prompt, >>, in a similar manner to the way in
which we have created Matlab functions. However, in some cases these will not
contain output parameters, but will instead output the information using print
statements.
Consider the following program, which has the radius of a circle as the input
parameter and then calculates, and prints out, the circumference and area of the
circle.
circle.m
function circle(r)
% VARIABLES
% r - radius of the circle (input)
% circumf - circumference of the circle
% area - area of the circle
circumf=2*pi*r;
area=pi*r^2;
end
Sample output is
>> circle(5)
59
4.2 Controlling Iterations
Here we consider a program in which we need to use both for loops and if
statements to control iterations.
2
Let a be a non-zero positive real number. For any x 0 satisfying 0 x 0 , the
a
recursive sequence defined by
xn1 xn 2 a xn
1
converges to .
a
So, the inverse of a number can be found using only multiplications and subtractions.
Here, we use a Matlab program to calculate the inverse of any number a using this
sequence.
In order to define a stopping criteria for the iterations within the program, i.e. when it
has converged to a required accuracy, we need to be able to compare the difference
between the estimate of the inverse on the current iteration, x n1 , and its value on the
previous iteration, x n . The simplest way of doing this is to label/name the current
estimate as 'new' and the previous estimate as 'old' and then test if it is sufficiently
converged. If it is determined that another iteration needs to be performed, however,
then we no longer need the 'old' estimate and we can overwrite 'old' with 'new' prior
to the next iteration (i.e. only two terms of this sequence need to be saved at any
given time). It is also sensible to set a maximum number of iterations, in case the
sequence does not converge.
Note that in this program we also introduce the return statement, which is used to
cause an immediate return from the program under particular circumstances (i.e.
inappropriate input values or non-convergence of iterations). This is described in
further detail later in this section.
60
inverse.m
function inversea(a,x0,maxits,acc)
% INPUT PARAMETERS
% a - the number for which the inverse is to be evaluated
% x0 - the initial estimate of the inverse
% maxits - the maximum number of iterations allowed
% acc - the accuracy required
% LOCAL PARAMETERS
% old - the old approximation to the inverse
% new - the new approximation to the inverse
% count - the counter for the iterations
if a<=0
fprintf('Number for which inverse is to be evaluated
must be greater than zero\n');
return % successfully leave the program
end
61
old=x0;
fprintf('Iteration Estimate\n');
fprintf(' 0 %1.10f\n',old);
for count=1:maxits
new=old*(2-a*old);
fprintf(' %1i %1.10f\n',count,new);
% convergence test
if abs(new-old)<acc
fprintf('Convergence to accuracy of %1e is
achieved\n',acc);
fprintf('The inverse of %1.4f is %1.10f\n',a,new);
return; % successfully leave the program
else
old=new; % set old as the latest value and
continue
end
end
end
Note that when printing out the accuracy, which is likely to be a very small number,
e.g. 10 8 , we use the scientific format, denoted in a Matlab fprintf statement using e.
62
Using the program to determine 1/17 to an accuracy of 10 8 , with an initial estimate
of 0.05, we obtain
>> inversea(17,0.05,4,10^(-8))
Iteration Estimate
0 0.0500000000
1 0.0575000000
2 0.0587937500
3 0.0588235143
4 0.0588235294
Convergence to accuracy of 1.000000e-08 is not achieved
Current estimate of the inverse of 17.0000 is 0.0588235294
Try increasing the maximum number of iterations
Note that the maximum number of iterations was set to 4, so convergence was not
achieved. Now, increasing the maximum number of iterations we obtain
>> inversea(17,0.05,12,10^(-8))
Iteration Estimate
0 0.0500000000
1 0.0575000000
2 0.0587937500
3 0.0588235143
4 0.0588235294
5 0.0588235294
Convergence to accuracy of 1.000000e-08 is achieved
The inverse of 17.0000 is 0.0588235294
If inappropriate input values are used, then the appropriate error messages are
obtained, as in the following examples.
>> inversea(-17,0.05,12,10^(-8))
Number for which inverse is to be evaluated must be greater
than zero
63
Programming Tutorial 4
In order to keep a record of the Matlab programs that you create, and the output
generated for the test cases, I suggest you copy and paste both the program and the
Command Window output into a Word document, as described at the beginning of
programming tutorial 1.
Exercise 1.
Modify the program that you created for exercise 2 of programming tutorial 1, for
calculating the volume and surface area of a cylindrical water storage tank, so that
the height and radius are entered as input parameters in the call to the program,
rather than the program requesting these input values from the user, as it runs. Your
call to the program should have the form tank(h, r), where h is the height and r is the
radius.
Use your program to determine the volume and total surface area of the following
water tanks;- (i) height = 4.5, radius = 1.3 and (ii) height = 1.75, radius = 2.34.
Exercise 2.
Write a program to find the approximate value of the integral of a function f x from
x a to x b using the trapezium (trapezoidal) rule.
ba
Divide the interval a,b into n equal subintervals of length h .
n
The composite trapezium rule is:
b
h
f x dx f a 2f a h 2f a 2h ... 2f a n 1 h f b
a 2
Your call to the program should have the form Trapezium(a,b,n) with the program
printing out the integral estimate. The program should not produce any other output.
The function f x should be defined in a separate Script file, with the main program
using this function where appropriate. The program should include appropriate
comments.
64
Exercise 3.
Write a program which determines and prints out the number of real roots of a
quadratic equation ax 2 bx c 0 where a, b and c are real numbers. The input
parameters to the program (a, b and c) should be entered via the call to the program,
which will have the form roots(a,b,c). The program should then decide on the
number of real roots, print an appropriate message and, where applicable, print the
root(s).
Exercise 4.
The recursive sequence defined by
1 a
xn1 xn
2 xn
converges to a , for 0 a .
Write a program which uses this recursive sequence to evaluate the square root of
any positive number. The input parameters of the program should be the number, a,
for which the square root is to be evaluated, the initial estimate, x 0 , the accuracy
required and a maximum number of iterations. These parameters should be entered
with the call to the program, which should be of the form sqroota(a,x0,maxits,acc).
The program should print out each iteration as it is calculated and also the final
estimate of the square root. The iterations should stop when the required accuracy is
reached. It is recommended that rather than creating a program from scratch, you
instead modify the inversea program, which was demonstrated in the lecture.
Also, carry out appropriate tests to demonstrate that your program produces a
suitable message if an inappropriate value for a is entered or if convergence is not
achieved.
65