MATLAB M-FILES AND PROGRAMMING - Publishpublish.uwo.ca/~plawren/papers/AM2415_MATLAB_notes.pdf ·...

21
Chapter 1 MATLAB M-FILES AND PROGRAMMING 1.1 Introduction The course is based around the use of the internationally recognised software tool MATLAB . There is a comprehensive on-line help with the MATLAB software, there are numerous books and online tutorials written on MATLAB programming, searching the UWO library database is a good starting point. MATLAB - in its simplest form is a basic scientific calculator; in its sophisticated form it is a scientific, graphing, programmable, matrix algebra calculator with a set of toolboxes for advanced problem solving. The array of modern utilities involving state of the art algorithms make MATLAB a very powerful scientific computational tool. However MATLAB is an interpreted language and can execute more slowly than compiled languages. Just bear this is mind for large computations. 1.2 Revision of MATLAB Basics - NOT Lectured Invoke MATLAB – by clicking on the MATLAB icon. You are in the MATLAB Command Window - which is part of the MATLAB Desktop. Commands can be typed after the >> prompt. The MATLAB Environment The MATLAB desktop comes with a number of windows and tools which describe your current MATLAB environment. The main window is the Command Window. The other two windows are the Command History Window which displays the sequence of commands and outputs that have appeared in the Command Window, and the Launch Pad/Workspace window. MATLAB Commands are typed after the >> prompt in the Command Window. 1

Transcript of MATLAB M-FILES AND PROGRAMMING - Publishpublish.uwo.ca/~plawren/papers/AM2415_MATLAB_notes.pdf ·...

Chapter 1

MATLAB M-FILES ANDPROGRAMMING

1.1 Introduction

The course is based around the use of the internationally recognised software tool MATLAB .

There is a comprehensive on-line help with the MATLAB software, there are numerous books and onlinetutorials written on MATLAB programming, searching the UWO library database is a good starting point.

MATLAB

� - in its simplest form is a basic scientific calculator; in its sophisticated form it is a scientific, graphing,programmable, matrix algebra calculator with a set of toolboxes for advanced problem solving.

� The array of modern utilities involving state of the art algorithms make MATLAB a very powerfulscientific computational tool.

� However MATLAB is an interpreted language and can execute more slowly than compiled languages.Just bear this is mind for large computations.

1.2 Revision of MATLAB Basics - NOT Lectured

Invoke MATLAB – by clicking on the MATLAB icon.

You are in the MATLAB Command Window - which is part of the MATLAB Desktop.

Commands can be typed after the >> prompt.

� The MATLAB Environment

The MATLAB desktop comes with a number of windows and tools which describe your current MATLABenvironment.

The main window is the Command Window. The other two windows are the Command HistoryWindow which displays the sequence of commands and outputs that have appeared in the CommandWindow, and the Launch Pad/Workspace window.

MATLAB Commands are typed after the >> prompt in the Command Window.

1

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 2

� HELP features.

The Windows version of MATLAB contains a complete HELP browser - see Section 1.3.9 as well ascommand line HELP utilities.

Try typing help; help help; help who; help ls in the Command Window.

The lookfor command is also available on the command line.

This command will return all occurrences of a word.

Try typing help lookfor and lookfor tan.

� ARITHMETIC OPERATIONS

MATLAB as a desktop calculator. (Note anything after a % is a MATLAB comment.)

>> 7+9 % ans is a special MATLAB value

ans =

16

>> 7*9

ans =

63

>> 7^2

ans =

49

You must follow the laws of the algebra of real numbers with regard to precedence of operations, eg ∧

(power), */, then +−, with anything in parentheses (brackets () ) being evaluated first.

>> 53+4

ans =

57

>> 5*(3+4) % Calculate (3 + 4) first

ans =

35

� LAST-LINE EDITING

You have typed:

>> 5*(12.2+7.5 -2/9)/4.6

ans =

21.1715

However you meant to type 2.9 instead of 2/9

MATLAB has a simple line-editor process - 4 (uparrow) key recalls previous calculations; then useright . and left / arrow keys to shift on the line; use the Backspace key to delete; and insert text asrequired. The down arrow key scrolls through the previous commands.

� MATLAB ERROR MESSAGES

Tutors are always being asked what is wrong with my MATLAB ?.

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 3

Recognizing incorrect code is a matter of practice and commonsense. At this stage we will be mainlyconcerned with syntax errors - that is incorrect use of MATLAB statements.

MATLAB will give an error message where possible and you should make sure you read this carefully.However sometimes the message is not at all clear and may be the result of a progression of errors.

As a simple example:

>> 52+*7

??? 52+*7

|

Error: Unexpected MATLAB operator.

Note that the place where MATLAB believes the error to have occurred is marked.

MATLAB is trying to say that it really expected a value of some kind - say a number instead of twoarithmetic operators. However 52∗+7 would actually be executed since it is assumed you meant 52∗(+7)with the multiplication being performed first. In this case missing out the value would go undetected andhence cause a computational error.

� BUILT-IN FUNCTIONS

Just as a scientific calculator has keys to invoke special functions such as square-root, exponential,logarithms; trig functions etc, MATLAB also has built-in functions.

Mathematical MATLAB

√6.5 >> sqrt(6.5)

e6.5 >> exp(6.5)

ln 6.5 >> log(6.5) natural logarithm (base e)log 6.5 >> log10(6.5) common logarithm (base 10)sin(6.5) >> sin(6.5)

NOTE: arguments for trigonometric functions are taken to be in RADIANS

Try these:

Verify log(10000) is 4Verify ln(3.2 · 8.5) = ln(3.2) + ln(8.5)Verify 10 log10(100) = 100Verify e ln(3.5) = 3.5

� BUILT-IN VALUES

MATLAB has various built-in standard values which are obtained using common terminology.

You have already come across the ans special value which contains the result of a a command lineoperation.

The value for π is represented by the name pi in MATLAB .

Type >> pi to obtain a value.

Thus sin(60◦) is expressed as >> sin(60*pi/180)

Since MATLAB essentially works in complex arithmetic, the names i or j are associated with thestandard mathematical complex number i =

√−1

Type >> 1+2i to obtain a value. Note 1+2j will give the same result.

Note that these names may be assigned other values - it is a good habit to get into with MATLAB toavoid using these MATLAB names for other values.

� MODES or FORMATS for DISPLAYING OUTPUT DATA

Type >> help format

Then type

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 4

>> format long

>> pi

>> %then type in

>> format short

>> pi

Compare the output for each case.

The default is format short

� MATLAB VARIABLES

MATLAB allows you to assign names to numeric values. That is we can use variables

So far we have the built-in MATLAB variable ans

>> 3*9

ans =

27

>> 4*6

ans =

24

However it is clear that the value of ans will change for each calculation.

So let us assign names:

>> a=3*9

a =

27

>> b=4*6

b =

24

>> a*b

ans =

648

>> c=a*b

c =

648

However if you type A instead of a you will told A is undefined.

NOTE: This is because in MATLAB , names are CASE SENSITIVE

Also do NOT use the same names as MATLAB does for its functions etc.

� MATLAB WORKSPACE

The values you are working with are associated with variable names that tag memory locations. By typingthe command who you will obtain a list of such variables; whilst the command whos gives a detailedlist. This information is referred to as your workspace.

In order to clear your workspace the command clear can be used.

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 5

� REDUCING THE AMOUNT OF OUTPUT - SUPPRESSING OUTPUT

You may have noticed that you get every value echoed.

Try >> x0=10, v0=15, a=-9.81, t=5

This can be a real nuisance and so MATLAB has a way of suppressing this output.

Simply follow a variable name, expression, etc by a semi-colon ; (semi-colon)

Try >> x0=10; v0=15; a=-9.81; t=5;

(don’t forget to use the arrow keys to roll back the previous line and edit it)

If you want the value, simply type the variable name: >> t

� LONG LINES

If a line is too long, it may be continued by using three periods “. . . ”

For example for p = Aj L4

V +B V 3L2

1+j

we might type:

>> P = A*j*L^4 /V + ...

B*(V^3*L^2)/(1+j)

� COMMON MISTAKES

Note that the way we write mathematical expressions often implies the existence of arithmetic operationswithout the symbols being used explicitly.

In the expression for p above, multiplication is implied and must be explicitly written in MATLAB (orany programming language for that matter). This is a common cause of errors.

Also note that it is wise to use brackets (parentheses) to ensure calculations are carried out correctly,even if the original expression does not use them - often they are implied by the typesetting.

For example in the expression θ2π it should be realised that the factor 2π is the divisor and thus the

MATLAB should be written >> theta/(2*pi)

The code >> theta/2*pi is equivalent to θ2π which is clearly not what was intended.

This is another common cause of errors.

� OTHER DATA TYPES

In common with many programming languages MATLAB has a range of data types. The most commonones are double and char. double refers to numeric values including those in arrays (see later) whilst charrefers to string values.

For example we could set the variable str to a string of characters as follows:

>> str = 'This is a message for you'

str =

This is a message for you

� OUTPUTTING INFORMATION

If you wish for just the message in the string variable str to be output then supress output in the usualway and use the disp function to display the string.

>> str = 'This is a message for you';disp(str)

This is a message for you

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 6

The disp command can be used to display the values of numeric variables.

So far we have seen that output can be obtained by simply not putting a semi-colon (;) after anyexpressions or assignment statements; by typing a variable name, or by use of the disp command.

In order to produce readable output in a well presented layout, we need to use a variety of methods foroutput.

The standard style of output in most languages is a form of print command - namely fprintf in MATLAB(very similar to the C language).

Unfortunately in all languages one runs into the problem of formatting which is the cause of much grief.

We will make use of the fprintf command throughout the course so that by the time we have finishedyou should be an expert.

1.3 MATLAB Files

In this course it will be necessary to work with several MATLAB file structures. One such file is the MATLABDIARY file which is simply a record of all the output that occurs in the command window when the DIARYsession is activated. Other files are the script and function M-files. These files will involve using the MATLABeditor which is part of the MATLAB environment.

� USING THE DIARY FILE FEATURE

MATLAB has the facility for you to save everything you type and everything that is output in theCommand Window. This can be accomplished by using the diary command.

Type >> help diary

You can invoke or turn diary on by the command >> diary filename

Here filename is any name you care to use (it is a good idea to distinguish these files for easy reference- I suggest a .txt extension, for example lab1results.txt

You close your diary file, - turn off the diary process by using >> diary off.

Since computer software systems do not like files being open in different places. It pays to close the diaryfile before trying to edit the file.

The file produced is an ASCII text file and can be edited with the MATLAB editor.

� MATLAB M-files

MATLAB is designed to work with specially named files called M-files.

These files contain sets of MATLAB instructions and are identified by the extension .m

M-files are ASCII text files - that is they consist of lines of text, numerical values, special symbols thatform a set of MATLAB commands.

In this course we will consider two types of M-files - the basic SCRIPT M-file and the specialisedFUNCTION M-file.

MATLAB will look for files with a .m extension - the so-called M-files and execute them if you type thename as a command.

Thus if mighty.m is an M-file in your directory, >> mighty will cause MATLAB to look for a file calledmighty.m and execute the commands in that file.

Note that the extension is NOT included when invoking your M-file.

You can list your M-file by typing in the command >> type mighty

In order to construct an M-file you will need to use an editor. MATLAB has an accompanying editor,to invoke the editor either click on the “new script” icon in the toolbar or through the “File ⇒ New ⇒Script” or from the command window by typing >> edit .

M-file style

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 7

I tend to keep my variable names short to avoid excessive typing and over-verbose code that becomesdifficult to read in terms of a mass of characters which obscure the flow and intention of the code. Thereis optimal level in my opinion.

Example of a MATLAB script M-file:

EXAMPLE 1.3.1:

Consider the volume V of liquid in a spherical tank of radius r as given by the formula V =πh2(3r − h)

3where h is the depth of the liquid.Write an M-file to calculate V for the values r = 1m, h = 0.7m.

The procedure for this is :

1. Set up the mathematical model/equation for the problem - given in this case.

2. Design your algorithm (straight forward in this case).

3. Use the editor to type in your MATLAB statements - save as say myliquid.m

4. Try executing your M-file in MATLAB by typing >> myliquid

5. If there is an error, or you wish to modify what you have done - simply edit the M-file and executeit again.

The editor can be invoked by clicking on File at the top left hand corner of the MATLAB window, andselecting New and then M-File from the drop-down menu. An editor window will then appear and thecommands can be typed in just as you would in the command window.

Note that you are supplying a logical sequence of instructions that are going to be executed one afterthe other in sequence and hence the order is important. For example, assign values to variables beforeusing those variables in expressions.

Thus type into the editor screen the following and then Save As the file myliquid.m.

- - - - - - - - - - - - the following is a MATLAB script M-file listing - - - - - - - - - - - -

% MATLAB Script file: myliquid.m

%

% Purpose: To calculate the volume of liquid in a spherical tank of

% radius r.

%

% Define variables:

% Input: r -- radius of the tank in metres

% h -- depth of the fluid in metres

% Output: V -- volume of the fluid in cubic metres

%

% Output a title for the problem output data

disp(' ')

disp('### CALCULATION OF THE VOLUME OF LIQUID IN A SPHERICAL TANK ###')

disp(' ')

% Assign values to r and h

r=1; h=0.7;

% Output input values

% The %5.1f is a format for the output

% - occupy 5 positions with one decimal place , in fixed point mode

fprintf('The tank has radius r=%5.1f metres \n',r)

fprintf('The depth of the liquid is h=%5.1f metres \n',h)

% Calculate the volume of liquid

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 8

V=pi*h^2*(3*r-h)/3;

% Output the Volume

fprintf('The volume of liquid is V=%10.2f cubic metres \n',V)

% Terminate the output with a statement

disp(' ')

disp('##### END OF VOLUME CALCULATION ##### ')

disp(' ')

% End of script myliquid.m

- - - - - - - - - - - - end of MATLAB script M-file listing - - - - - - - - - - - -

Having saved the commands typed into the editor in the file myliquid.m you are now in a position torun or execute the file. To do this:

Type >> myliquid

to run (execute) the M-file in the command window. MATLAB will look for a file called myliquid.m(using the MATLAB path which will include your current directory as first choice) and proceed to executethe commands in the file.

In order to illustrate a typical final run (that is when all the bugs have been sorted out) consider thefollowing code and output that would appear in the command window and, in this case, be collected inthe diary file, myliquid.txt:

- - - - - - - - - - - - the following is MATLAB command window contents - - - - - - - - - - - -

>> diary myliquid.txt % Turn a diary file on - using filename myliquid.txt

>> type myliquid % List the M-file -

>> % produces as output the commands in myliquid.m

% MATLAB Script file: myliquid.m

%

% Purpose: To calculate the volume of liquid in a spherical tank of

% radius r.

%

% Define variables:

% Input: r -- radius of the tank in metres

% h -- depth of the fluid in metres

% Output: V -- volume of the fluid in cubic metres

%

disp(' ')

disp('### CALCULATION OF THE VOLUME OF LIQUID IN A SPHERICAL TANK ###')

disp(' ')

% Assign values to r and h

r=1; h=0.7;

% Output input values

fprintf('The tank has radius r=%5.1f metres \n',r)

fprintf('The depth of the liquid is h=%5.1f metres \n',h)

% Calculate the volume of liquid

V=pi*h^2*(3*r-h)/3;

% Output the Volume

fprintf('The volume of liquid is V=%10.2f cubic metres \n',V)

disp(' ')

disp('##### END OF CALCULATION #####')

% End of script myliquid.m

>> myliquid % Run (execute) the M-file - produces the output from the M-file

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 9

### CALCULATION OF THE VOLUME OF LIQUID IN A SPHERICAL TANK ###

The tank has radius r= 1.0 metres

The depth of the liquid is h= 0.7 metres

The volume of liquid is V= 1.18 cubic metres

##### END OF CALCULATION #####

>> diary off % Turn the diary file off - close the file

- - - - - - - - - - - - end of MATLAB command window contents - - - - - - - - - - - -

So the diary file now contains all the details output in the command window including a listing of thecommands in the M-file and the output produced by executing the M-file.

You can edit the diary file to remove any spurious unwanted output accidently produced for example.

The file myliquid.txt could then be sent to the printer to obtain hard-copy.

1.4 Examples of Structures in Programming -While Loops and Branching

EXAMPLE 1.4.1:

Reconsider the problem and code of EXAMPLE 1.3.1 only this time we will set up a structure for handling anumber of different values for h which will be entered on request from the keyboard.

Basically we shall use a while statement to achieve our purpose.

If we describe what we want to do in plain English, using a pseudo-code notation, then we should be able towrite the MATLAB code.

1. Input first h value

2. Calculate the volume of liquid

3. Input another value of h and repeat step 2.

So we have a loop where we just keep repeating commands.

Clearly the process will stop when we run out of h values. To program this we can ask the question: is therea value for h?

To implement this test we can use a MATLAB function called isempty which simply checks on the state ofh. Basically did you enter a value or simply hit the enter key.

So we can continue the looping process while h is not empty - written as while ∼isempty(h)

We will also present the output in a table and will need to set up table headers.

Thus the code now becomes:

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 10

- - - - - - - - - - - - the following is a MATLAB script M-file listing- - - - - - - - - - - -

% MATLAB Script file: myliquid2.m

%

% Purpose: To calculate the volume of liquid in a spherical tank of

% radius r for values of the depth of fluid , h.

%

% Define variables:

% Input: r -- radius of the tank in metres

% h -- depth of the fluid in metres

% Output: V -- volume of the fluid in cubic metres

%

% Output a title for the problem output data

disp(' ')

disp('### CALCULATION OF THE VOLUME OF LIQUID IN A SPHERICAL TANK ###')

disp(' ')

% Assign a value to r

r=1;

% Output input values

% The %5.1f is a format for the output

% - occupy 5 positions with one decimal place , in fixed point mode

fprintf('The tank has radius r=%5.1f metres \n',r)

% Set up headers for the table of output of h and V

disp('=================================================== ')

fprintf(' Depth of liquid Volume of liquid \n')

fprintf(' h metres V cubic metres \n')

disp('=================================================== ')

% Input the first value of h

h=input('Input a value for the depth h (hit enter to stop): ');

% Use a while loop to repeat calculation of volume for various h values

% Terminate while loop if h has no value - that is continue to loop

% while h is not empty

while ~isempty(h)

fprintf('The depth of the liquid is h=%5.1f metres \n',h)

% Calculate the volume of liquid

V=pi*h^2*(3*r-h)/3;

% Output h and the corresponding Volume in a table

fprintf('%10.2f %10.2f \n',h,V)

% Input another value for h (hit enter to stop)

h=input('Input a value for the depth h (hit enter to stop): ');

end % end of the range of the while loop

% Terminate the output with a statement

disp(' ')

disp('##### END OF VOLUME CALCULATION ##### ')

disp(' ')

% End of script myliquid2.m

- - - - - - - - - - - - end of MATLAB script M-file listing - - - - - - - - - - - -

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 11

EXAMPLE 1.4.2:

Typical output is:

- - - - -the following is output from a MATLAB script M-file- - - - - - -

>> myliquid2 % Execute the M-file myliquid2.m - Output appears below

### CALCULATION OF THE VOLUME OF LIQUID IN A SPHERICAL TANK ###

The tank has radius r= 1.0 metres

===================================================

Depth of liquid Volume of liquid

h metres V cubic metres

===================================================

Input a value for the depth h (hit enter to stop): 0.3

0.30 0.25

Input a value for the depth h (hit enter to stop): 0.5

0.50 0.65

Input a value for the depth h (hit enter to stop):

##### END OF VOLUME CALCULATION #####

- - - - -end of output from a MATLAB script M-file- - - - - - -

This output is interspersed with input requests so let us modularize the algorithm so that we save the outputvalues h and V as rows of an array and output that array. This means moving the output section to the endof the code to follow the lines produced by the input requests.

Thus we have the array version of our program:

- - - - - - - - - - the following is a MATLAB script M-file listing- - - - - - - - - -

% MATLAB Script file: myliquid2a.m

%

% Purpose: To calculate the volume of liquid in a spherical tank of

% radius r for values of the depth of fluid , h.

%

% Define variables:

% Input: r -- radius of the tank in metres

% h -- depth of the fluid in metres

% Output: V -- volume of the fluid in cubic metres

%

% Print a title for the problem output data

disp(' ')

disp('### CALCULATION OF THE VOLUME OF LIQUID IN A SPHERICAL TANK ###')

disp(' ')

% Assign a value to r

r=1;

% Initialize an array to null to hold the output of h and V

out_table =[];

% Input the first value of h

h=input('Input a value for the depth h (hit enter to stop): ');

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 12

% Use a while loop to repeat calculation of volume for various h values

% Terminate while loop if h has no value - that is continue to loop

% while h is not empty

while ~isempty(h)

% Calculate the volume of liquid

V=pi*h^2*(3*r-h)/3;

% Put h and the corresponding Volume in an array

% Add columns since fprintf statement will output

% column by column

out_table =[ out_table [h; V]];

% There are lots of variations for this but in this form

% out_table itself will look like a data set as presented in many texts

% Input another value for h (hit enter to stop)

h=input('Input a value for the depth h (hit enter to stop): ');

end % end of the range of the while loop

% OUTPUT SECTION

% Output input values

% skip 2 lines (\n)

fprintf('\n\n ****** OUTPUT FOR FLUID IN A SPHERICAL TANK ****** \n\n')

% The %5.1f is a format for the output

% - occupy 5 positions with one decimal place , in fixed point mode

fprintf('The tank has radius r=%5.1f metres \n',r)

% Set up headers for the table of output of h and V

disp('=================================================== ')

fprintf(' Depth of liquid Volume of liquid \n')

fprintf(' h metres V cubic metres \n')

disp('=================================================== ')

fprintf('%10.2f %10.2f \n',out_table)

disp('=================================================== ')

% Terminate the output with a statement

disp(' ')

disp('##### END OF VOLUME CALCULATION ##### ')

disp(' ')

% End of script myliquid2a.m

- - - - - - - - - - end of MATLAB script M-file listing - - - - - - - - -

The output would then look like:

- - - - -the following is output from a MATLAB script M-file- - - - - - -

>> myliquid2a % Execute the M-file myliquid2a.m - Output appears below

### CALCULATION OF THE VOLUME OF LIQUID IN A SPHERICAL TANK ###

Input a value for the depth h (hit enter to stop): 0.2

Input a value for the depth h (hit enter to stop): 0.5

Input a value for the depth h (hit enter to stop): 0.8

Input a value for the depth h (hit enter to stop): 1

Input a value for the depth h (hit enter to stop): 1.3

Input a value for the depth h (hit enter to stop): 1.7

Input a value for the depth h (hit enter to stop): 1.9

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 13

Input a value for the depth h (hit enter to stop):

****** OUTPUT FOR FLUID IN A SPHERICAL TANK ******

The tank has radius r= 1.0 metres

===================================================

Depth of liquid Volume of liquid

h metres V cubic metres

===================================================

0.20 0.12

0.50 0.65

0.80 1.47

1.00 2.09

1.30 3.01

1.70 3.93

1.90 4.16

===================================================

##### END OF VOLUME CALCULATION #####

- - - - -end of output from a MATLAB script M-file- - - - - - -

NOTE: At this stage it should be mentioned again that it is a good idea to type clear all before runningprograms in order to ensure all variables are reset.

EXAMPLE 1.4.3:

Let us reconsider our problem again so that this time we check for say negative input values.

For this we need a branching structure of the form:

if <a test is true >

% [execute this block (A) of statements]

else

% [execute this block (B) of statements]

end

Basically what is needed is that the calculation is performed if h ≥ 0 but if h is negative then we will print amessage to that extent and ask for another value of h.

Thus our program becomes:

- - - - - - - - - - the following is a MATLAB script M-file - - - - - - - - - -

% MATLAB Script file: myliquid3.m

%

% Purpose: To calculate the volume of liquid in a spherical tank of

% radius r for values of the depth of fluid , h.

% Include a test for a negative h value

%

% Define variables:

% Input: r -- radius of the tank in metres

% h -- depth of the fluid in metres

% Output: V -- volume of the fluid in cubic metres

%

% Output a title for the problem output data

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 14

disp(' ')

disp('### CALCULATION OF THE VOLUME OF LIQUID IN A SPHERICAL TANK ###')

disp(' ')

% Assign a value to r

r=1;

% Initialize an array to null to hold the output of h and V

out_table =[];

% Input the first value of h

h=input('Input a value for the depth h (hit enter to stop): ');

% Use a while loop to repeat calculation of volume for various h values

% Terminate while loop if h has no value - that is continue to loop

% while h is not empty

while ~isempty(h)

% Test to see if h<0 and branch accordingly

if h >= 0

% These are the block A statements

% if h is ok carry on with calculation

% Calculate the volume of liquid

V=pi*h^2*(3*r-h)/3;

% Put h and the corresponding Volume in an array

% Add columns since fprintf statement will output

% column by column

out_table =[ out_table [h; V]];

% There are lots of variations for this but in this form

% out_table will look like a data set as presented in many texts

% end of block A statements

else

% These are the block B statements , executed only if h<0

% else if h is negative , output a message and get another h value

% these are

fprintf (['\n !! DATA ERROR: a negative h value was entered ,' ,...

'get another h value!! \n'])

% end of block B statements

end

% Whatever the outcome:

% Input another value for h (hit enter to stop)

h=input('Input a value for the depth h (hit enter to stop): ');

end % end of the range of the while loop

% OUTPUT SECTION

% Output input values

% skip 2 lines (\n)

fprintf('\n\n ****** OUTPUT FOR FLUID IN A SPHERICAL TANK ****** \n\n')

% The %5.1f is a format for the output

% - occupy 5 positions with one decimal place , in fixed point mode

fprintf('The tank has radius r=%5.1f metres \n',r)

% Set up headers for the table of output of h and V

disp('=================================================== ')

fprintf(' Depth of liquid Volume of liquid \n')

fprintf(' h metres V cubic metres \n')

disp('=================================================== ')

fprintf('%10.2f %10.2f \n',out_table)

disp('=================================================== ')

% Terminate the output with a statement

disp(' ')

disp('##### END OF VOLUME CALCULATION ##### ')

disp(' ')

% End of script myliquid3.m

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 15

- - - - - - - - - - end of MATLAB script M-file listing - - - - - - - - -

- - - - -the following is output from a MATLAB script M-file- - - - - - -

>> myliquid3 % Execute the M-file myliquid3.m - Output appears below

### CALCULATION OF THE VOLUME OF LIQUID IN A SPHERICAL TANK ###

Input a value for the depth h (hit enter to stop): 0.3

Input a value for the depth h (hit enter to stop): 0.5

Input a value for the depth h (hit enter to stop): -1

!! DATA ERROR: a negative h value was entered , get another h value !!

Input a value for the depth h (hit enter to stop): 1

Input a value for the depth h (hit enter to stop):

****** OUTPUT FOR FLUID IN A SPHERICAL TANK ******

The tank has radius r= 1.0 metres

===================================================

Depth of liquid Volume of liquid

h metres V cubic metres

===================================================

0.30 0.25

0.50 0.65

1.00 2.09

===================================================

##### END OF VOLUME CALCULATION #####

- - - - -end of output from a MATLAB script M-file- - - - - - -

1.5 Examples of Structures in Programming -For Loops - Counting or Stepping a Proscribed Number of Times

The other type of loop which I use to do what it was intended for - repeat a process a set number of times- is the for loop.

In numerical work we often have need to step from one point to another, or to iterate a process a number oftimes.

EXAMPLE 1.5.1: Constructing an Iterative Process

Consider the following problem which affects most of us at some time:

Suppose you borrow $10,000 and are told that if you make repayments at a certain rate of $Rper month you will have repaid the debt in N months.

The question is whether you are indeed borrowing the money at the quoted interest rate say11.5%.

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 16

The first thing we shall do is to set up a mathematical model representing the problem.

Mathematical Model

Let P be the amount borrowed. let the rate of interest to be determined be r% per annum.

Let Ak be the amount after the kth time interval (months).

Then the amount owing at the end of the kth time interval, Ak, is obtained from the amount owing at theend of the previous time interval, plus the interest, less the repayment.

In mathematical terms this is simply: Ak = Ak−1 + Ak−1 ×r

1200− R

The interest rate needs to be expressed as a decimal and per month hence the factor 1200.

Thus we have Ak − Ak−1(1 +r

1200) = −R, k = 1(1)N

This is the model definition which is a difference equation (a discrete version of a differential equation) whichcan be solved in much the same way as you solved differential equations in your mathematics courses.

This is a first order linear equation with solution Ak = C(1 +r

1200)k +

1200R

r, k = 0(1)N

where C is an arbitrary constant.

Now apply the known conditions:

� when k = 0, A0 = P , so P = C +1200R

r

Thus C = P − 1200R

r.

� when k = N , AN = 0, so that we have 0 = (P − 1200R

r)(1 +

r

1200)N +

1200R

r

Introduce a new non-dimensional variable x =r

1200(in this case the new variable x is not in percentages).

Then we have:

0 = (P − R

x)(1 + x)N +

R

x

We have created the equation to be solved for the problem.

We need a SOLVER process for this equation.

The equation is a nonlinear equation in the unknown x

To solve it let us take a simplistic approach and ignore for the moment the (1+x)N term as involving x so wecan solve the equation for x in the other terms as:

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 17

x =R((1 + x)N − 1)

P (1 + x)N

Now if we had a value for x, an initial guess say, we could use it to evaluate the righthand-side which wouldgive us a new value for x.

This process could be repeated until, hopefully, the value of x does not change. This would mean the processhas converged.

This process is referred to as an ITERATIVE process and is a key process in numerical mathematics.

The next question should be: How do we obtain an initial guess?

Often the problem suggests a procedure. In this case since x is small we could approximate (1 + x)N by thefirst TWO terms in the series expansion: (1 + x)N ≈ 1 + Nx

This a linear approximation and using this in the equation gives x ≈ R((1 + Nx) − 1)

P (1 + x)Nor (1 + x)N ≈ RN

P

This equation is precisely what you would get if you took no account of repayments until the end so that youhad compound interest on P over N months so that the total to be repaid would be P (1 + x)N = RN

Putting the given values in gives x = 0.006 and r = 1200x = 7.15%

Now we know that this is rather low since the quoted rate was 11.5% giving x = 0.0096 so let us simply doubleour simple compound interest value as our initial value for x.

Then we have the iterative process:

xk =R((1 + xk−1)

N − 1)

P (1 + xk−1)Nk = 1, 2, 3, . . . where x0 = 2c, c = (

RN

P)

1N − 1

EXAMPLE 1.5.2: Programming an Iterative Process

The iterative process can be coded in MATLAB as follows. Most of the code is comments and outputstatements which is typical of most computer programs in any language.

- - - - - - - - - - - - the following is a MATLAB script M-file - - - - - - - - - - - -

% Script file myinterest.m

%

% Purpose: To calculate the true interest rate on a loan of $P

% given the monthly repayments and the number of

% repayments

%

% Problem variables:

% Input variables:

% P - the loan amount (pricipal)

% R - the monthly repayment

% N - the number of months

% q - the quoted interest rate % per annum

% Output variables:

% r - the true interest rate % per annum

%

% Internal variables:

% x - the nondimensional monthly rate

% c - the rate from simple compound formula

% Iteration variables

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 18

% maxits - maximum number of iterations permitted

% k -- iteration counter

%

% Output a title for the problem output data

disp(' ')

disp('### CALCULATION OF THE TRUE RATE OF INTEREST ON A LOAN ###')

disp(' ')

% Input the data values

P=input('Input a value for the principal of the loan: ');

N=input('Input a value for the number of months of the loan: ');

R=input('Input a value for the monthly repayments on the loan: ');

q=input('Input a value for the quoted annual % interest rate for the loan: ');

% Ouput the data values:

disp('========================================================================== ')

fprintf('\nThe principal of the loan is $%8.2f borrowed over %4.0f months \n',P,N)

fprintf('The monthly repayments are $%6.2f \n',R)

fprintf('on a quoted interest rate of %5.2f%% per annum \n',q)

% Set up a maximum number of iterations in case the iterative process takes

% too long

maxits =20;

% Calculate initial value for the interest variable x

c=(N*R/P)^(1/N)-1; x=2*c; r=1200*x;

k=0; % set iteration counter k=0 for output purposes

% output headers for the table of values

fprintf('\n\n k x r \n')

disp('======================================================= ')

% output initial values

fprintf(' %5.0f %10.4f %10.2f \n',k,x,r)

% The iterative loop uses a for loop to simply count through the

% number of iterations - an increment of 1 is the default

for k=1: maxits

xN=(1+x)^N; % use an intermediate variable to do this once

% use the iterative formula to generate a new x value

x=R*(xN -1)/(P*xN);

% calculate the % interest rate r=1200x

r=1200*x;

% output a table of values

fprintf(' %5.0f %10.4f %10.2f \n',k,x,r)

end % end of range of the iterative for loop

fprintf('\n The true rate of interest is in fact %8.2f%% \n\n',r)

% Terminate the output with a statement

disp(' ')

disp('##### END OF INTEREST RATE CALCULATION ##### ')

disp(' ')

% End of script myinterest.m

- - - - - - - - - - end of MATLAB script M-file listing - - - - - - - - -

Execution of myinterest.m will produce the OUTPUT:

- - - - -the following is output from a MATLAB script M-file- - - - - - -

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 19

>> myinterest % Execute the M-file myinterest.m - Output appears below

### CALCULATION OF THE TRUE RATE OF INTEREST ON A LOAN ###

Input a value for the principal of the loan: 10000

Input a value for the number of months of the loan: 36

Input a value for the monthly repayments on the loan: 343.98

Input a value for the quoted annual % interest rate for the loan: 11.5

==========================================================================

The principal of the loan is $10000 .00 borrowed over 36 months

The monthly repayments are $343 .98

on a quoted interest rate of 11.50% per annum

k x r

=======================================================

0 0.0119 14.29

1 0.0119 14.33

2 0.0120 14.35

3 0.0120 14.37

4 0.0120 14.39

5 0.0120 14.40

6 0.0120 14.41

7 0.0120 14.42

8 0.0120 14.43

9 0.0120 14.43

10 0.0120 14.44

11 0.0120 14.44

12 0.0120 14.44

13 0.0120 14.44

14 0.0120 14.45

15 0.0120 14.45

16 0.0120 14.45

17 0.0120 14.45

18 0.0120 14.45

19 0.0120 14.45

20 0.0120 14.45

The true rate of interest is in fact 14.45%

##### END OF INTEREST RATE CALCULATION #####

- - - - -end of output from a MATLAB script M-file- - - - - - -

As is often the case because of the manner in which the computations are carried out in financial institutionsyou find you are being overcharged. Worst case scenarios of double the quoted rate as exercised in manyhire purchase schemes resulted in Government action a number of years ago to insist the true rate is quoted.However there have been a number of cases involving financial institutions in regard to this problem. Since allof us including engineers borrow money then it is worth knowing something about loans and interest.

In order to organise the output in a more tractable tabular form (you could also leave out the formatting anduse disp instead of fprintf, the following revised form of the interest code is given. Here the iteration valuesare stored in an array.

- - - - - - - - - - - - the following is a MATLAB script M-file - - - - - - - - - - - -

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 20

% Script file myinterest_rev.m

% --------------------------------------------------------------

% Purpose: To calculate the true interest rate on a loan of $P

% given the monthly repayments and the number of

% repayments

% --------------------------------------------------------------

%

% Problem variables:

% --------------------------------------------------------------

%

% Input variables:

% P - the loan amount (pricipal)

% R - the monthly repayment

% N - the number of months

% q - the quoted interest rate % per annum

%

% Output variables:

% r - the true interest rate % per annum

%

% Internal variables:

% x - the nondimensional monthly rate

% c - the rate from simple compound formula for initial x

% Iteration variables

% maxits - maximum number of iterations permitted

% k -- iteration counter

%

clear all % Clear Workspace

clc % Clear Screen

% Start Coding

% --------------------------------------------------------------

% Screen title for the problem

disp(' ')

disp('### CALCULATION OF THE TRUE RATE OF INTEREST ON A LOAN ###')

disp(' ')

% Input the data values

P=input('Input a value for the principal of the loan: ');

N=input('Input a value for the number of months of the loan: ');

R=input('Input a value for the monthly repayments on the loan: ');

q=input('Input a value for the quoted annual % interest rate for the loan: ');

% --------------------------------------------------------------

% --------------------------------------------------------------

% CORE

% --------------------------------------------------------------

% Set up a maximum number of iterations in case the iterative process takes

% too long

maxits =20;

% Calculate initial value for the interest variable x

c=(N*R/P)^(1/N)-1;

x=2*c;

r=1200*x;

res (1 ,:)=[0 x r]; % Store initial values in result matrix row1

% contains the initial values

% The iterative loop uses a for loop to simply count through the

% number of iterations - an increment of 1 is the default

for k=1: maxits

xN=(1+x)^N; % use an intermediate variable to do this once

% use the iterative formula to generate a new x value

x=R*(xN -1)/(P*xN);

% calculate the % interest rate r=1200x

r=1200*x;

% store solution in result matrix - row by row - start from row2

res(k+1 ,:)=[k x r];

end % end of range of the iterative for loop

% --------------------------------------------------------------

% --------------------------------------------------------------

AM2415 2010 - Course Support Notes September 27, 2010. Bob Broughton & Piers Lawrence 21

% Output the data values:

% --------------------------------------------------------------

clc % Clear input screen

% Output title for the problem

disp(' ')

disp('### CALCULATION OF THE TRUE RATE OF INTEREST ON A LOAN ###')

disp(' ')

fprintf('\nThe principal of the loan is $%8.2f borrowed over %4.0f months \n',P,N)

fprintf('The monthly repayments are $%6.2f \n',R)

fprintf('on a quoted interest rate of %5.2f%% per annum \n',q)

% OUTPUT TABLE OF ITERATION VALUES

% output headers for the table of values

fprintf('\n k x r \n')

disp('======================================================= ')

% output table - note MATLAB prints by column from an array , so transpose

% the array to obtain the row by row table.

fprintf(' %5.0f %10.4f %10.2f \n',res ')

% output true interest rate

fprintf('\n The true rate of interest is in fact %8.2f%% \n\n',r)

% Terminate the output with a statement

disp('##### END OF INTEREST RATE CALCULATION ##### ')

% End of script myinterest_rev.m

- - - - -end of output from a MATLAB script M-file- - - - - - -

QUESTIONS arising from the calculation might be:

� Can we stop the process sooner if it is clear convergence has taken place?

For example in this case could we jump out iteration 15? - Answer yes by using the relative error test.

� What happens if we don’t get convergence?

How do we direct the program to deal with convergence and non-convergence?