You are on page 1of 24

UNIVERSITY OF NOTTINGHAM Chemical and Environmental Engineering

H82CSY Computer Systems Dr Paul Langston September 2009

Introduction to MATLAB Programming

Acknowledgements to: Dr J A Wilson, Dr Gan Suyin

Matlab is a technical computing environment for high-performance numeric


computation and visualisation. Matlab integrates numerical analysis, matrix
computation, signal processing and graphics in an easy-to-use environment where
problems and solutions are expressed just as they are written mathematically -
without traditional programming.

Matlab is an interactive system whose basic data element is a matrix that does not
require dimensioning. This allows you to solve many numerical problems in a
fraction of the time it would take to write a program in a language such as Fortran,
Basic, or C.

Fundamental Programming Concepts:

DATA ----- PROGRAM ------- RESULTS

DATA: numbers in a file, key presses, mouse clicks… ie INPUTS

PROGRAM: (software) Series of executable expressions often hidden from user (eg
Hysys, Word, Windows XP)

Results: numbers written to a file, lines drawn on a screen …. ie OUTPUTS

Results from one program can become data for another program.

CPU: Central Processor Unit – this controls operations and undertakes the
calculations.

RAM: Random Access Memory: where the CPU stores and accesses information
during calculations.

You do not need to know much about the hardware to develop software.

Reference
Matlab 6 for Engineers, Adrian Biran & Moshe Breiner, 3rd ed 2002, Prentice Hall
Some examples have been taken from this text.

As of date above we are using Matlab version 7.8 2009.


Access via App-V see Figure
Be patient while it opens.

1
Why learn Matlab Programming?

• Potentially useful in later modules such as project modules

• Useful for Simulink program in process dynamics & control module

• Good exercise in logical thinking

• Useful if you undertake programming in other languages

• Improved understanding of implications when using software (see errors and


uncertainty in scientific programming)

Errors and Uncertainty

Ref: An Introduction to Computational Fluid Dynamics. H K Versteeg, W Malalasekera

Note we will not be doing any CFD in this module but the principles here are
generally relevant in any scientific programming.

Errors – ie not caused by lack of knowledge


• Numerical – roundoff errors, convergence errors
• Coding – mistakes (bugs)
• User

Uncertainty – due to lack of knowledge


• Inaccurate data input
• Physical model

“Coding and user errors are the most insidious forms of errors. The well publicized
failure on 23 September 1999 of NASA’s Mars Climate Orbiter space mission was
subsequently attributed to incompatibility between pieces of software written in
Imperial units…”

You will see that Matlab can detect some errors, for example where the correct
syntax is not used, or when it runs, for example dividing by zero is a common
programming run time error. However, the worst type of error is one where the
program runs and produces a result that is not obviously wrong as in above
example.

Another example of a problem with software that I can think of is the design of the
Millenium Bridge in London (pedestrian only). When people first used it, it wobbled
significantly. It had to be closed and further damping added.

2
SESSION 1

1.1 MATLAB Environment

Starting MATLAB launches the Desktop which has 3 default windows:

 Workspace or Current Directory


 Command History
 Command Window

On the most basic level, the Command window can be used for simple mathematics;
most commands are much the same as those familiar from calculators (one notable
exception is the natural logarithm ln x which becomes log(x)). Typing directly into
the command window is referred to as interactive mode. The alternative is to run
from script files.

= is called the assignment or replacement operator (the LHS is replaced by the


RHS, thus the LHS must be a single variable and the RHS must be computable) for
example x=3
Once a variable is assigned, MATLAB remembers it until it is overwritten or cleared
(clear x for the example above). It is therefore useful to start exercises with clear
all. If in doubt whether a variable already exists, who or whos lists them.

Rules for variable names:


 Up to 63 alphanumerical characters
 Must start with either an uppercase or lowercase letter, which can then be
followed by any combination of uppercase and lowercase letters, numbers and
underscore (_)
 No blank spaces
 Variable names are case sensitive

clc clears the command window.

A semicolon (;) at the end of an expression suppresses the answer being printed on
screen.
↑ recalls previous lines (useful for editing out errors)

Arithmetic Operation Arithmetic Operators


Addition +
Subtraction -
Multiplication *
Division /
Exponentiation ^

Hierarchy of MATLAB operations:


Parentheses, exponentiation, multiplication/division, addition/subtraction. Operations
from left to right.

3
1.2 MATLAB Built-In Functions

Function MATLAB Inverse


Mathematical Functions ex exp(x)
√x sqrt(x)
ln(x) log(x)
log10(x) log10(x)
|x| abs(x)

Trigonometric Functions sine sin(x) asin(x)


cosine cos(x) acos(x)
tangent tan(x) atan(x)
secant(x) sec(x) asec(x)
cosecant csc(x) acsc(x)
cotangent cot(x) acot(x)

Hyperbolic Functions sine sinh(x) asinh(x)


cosine cosh(x) acosh(x)
tangent tanh(x) atanh(x)
secant sech(x) asech(x)
cosecant csch(x) acsch(x)
cotangent coth(x) acoth(x)

Mathematical Constants π pi
∞ inf

1.3 Types of Files

Mat-Files - extension .mat - save all workspace variables created during a session
in a binary file.
To save a session, type save filename.mat or save filename in the Command
window.
To retrieve the file, type load filename.mat or load filename.
Default is the 'work' directory in the MATLAB folder; cd (change directory) if you
need to save it elsewhere, e.g. cd z:\ to save to your server space; what list the
files in the current directory.

Two types of MATLAB Editor files (M-files): script (program) files and function files

M-Files – extension .m – saved in American Standard Code for Information


Interchange (ASCII) format, can be created and read by external text editors; they
are executed by typing their name (without extension) into the Command window.
To create a new M-file, click File > New > M-file
On the most basic level, the advantage of using the Editor is that it allows changes
to be made (whereas commands cannot be changed easily when typed into the
Command window).
Good practice to start each new session with the functions clc and clear all. Also
include comments explaining what the M-file does; a comment is preceded by %.
Note m-files can call other m-files (ie sub programs).

4
1.4 Arrays and Matrices

The two classes of arrays that are commonly encountered in MATLAB are numeric
and character. For numeric arrays:

An array A of m rows and n columns is called a matrix of order (m x n)

 a11 a12 L a1n 


a 
 21 a22 
M 
 
 am1 amn 

When there is only one column A is called a column matrix or vector. Likewise when
there is only one row A is a row matrix or vector. Elements in a vector are separated
by blank spaces or commas. In matrices, rows are separated by semicolons.

Example: A=[1 2 3; 4 5 6; 1 3 5] Assigns data to a 3x3 matrix A

The colon notation to create a vector is


x = s:d:f OR x = (s:d:f) OR x = [s:d:f]

where s = start or initial value


d = increment or decrement
f = end or final value

Generation of n equally spaced values starting at s and ending at f:


x = linspace(s,f,n)
If n is not specified, MATLAB assigns it a value of 100.

An apostrophe (‘) transposes a matrix or vector.

When we add or subtract a scalar from a vector, the scalar is added or subtracted
from each element of the vector. For array (element-by-element) multiplication and
division, a dot (.) precedes * or /. Without the dot, the operation becomes a matrix
multiplication and division.

1.5 Mathematical Operations

On the basic mathematics level row vectors are useful for finding the roots of
polynominals using the roots command. Let f(x) be a polynomial of the form

f ( x) = c1 x n + c2 x n −1 + ... + cn x + cn +1

its roots can be found by typing the command roots(c)

where c = [c1, c2, …, cn+1].

5
Matrices can be used to solve simultaneous equations. Consider the following system
of n equations and n unknowns:

a11 x1 + a12 x2 + ... + a1n xn = b1


a21 x1 + a22 x2 + ... + a2 n xn = b2
M
an1 x1 + an 2 x2 + ... + ann xn = bn

This system of equations can be rewritten in matrix notation as follows:

Ax = b
 a11 a12 L a1n   x1   b1 
a a M   x2  b 
A =  21 22 ,x =  ,b =  2 
 M O   M  M
     
 an1 L amn   xn  bn 

To solve this system of equations type x=A\b

1.6 Strings

Character arrays are arrays containing strings, which are any combination of letters,
numbers and special characters. Used for displaying information to Command
window as well as annotating displayed data and graphs. Each character in a string
occupies one element in the array. To define a string, type all its characters between
a pair of single quotes (‘…’). For example, s=‘Who is he?’ or s=[‘Who is he?’]. To
convert a numerical value to a string, use the num2str command.

1.7 Data Input/Output

Use disp('text') to enable text to be displayed in the command window when


running an M-file. To display a variable, use disp(variable) or use the following
form to combine text and variable: disp([‘text’ num2str(variable)]. To prompt
user input, type variable = input ('text').

The format function can be used to control the output format of numeric information
to the command window. Use the help system to investigate.

1.8 Online Help

There are several ways to access the online help in MATLAB:

 Click on ? icon on the toolbar of the Command window.


 Select from the Help pull-down menu.
 To find out about a particular function, use the Index tab or type help
FunctionName in the Command window. Both ways present almost the same

6
information, except that the latter is in a less elegant format and sometimes
does not include equations.
For example, to investigate the format function search on: format in help.

EXAMPLES
% This introductory program greets you
% asks your name and , then it greets you by name
% and tells you the date
% From Biran & Breiner
% Aug 2008 P. Langston
% type this into a file Hello.m, then help Hello

disp('Hello who are you?')


name=input(' Please enter your name between quotes');
d=date;
answer= [' Hello ' name '. Today is ' d];
disp(answer)

In command window:

>>
>> clear all
>> help Hello
This introductory program greets you
asks your name and , then it greets you by name
and tells you the date
From Biran & Breiner
Aug 2008 P. Langston
type this into a file Hello.m, the help Hello

>> Hello
Hello who are you?
Please enter your name between quotes ' Paul'
Hello Paul. Today is 07-Aug-2008
>>

Note: comments should be used to help the user or


programmer. They need not be restricted to the first few
lines. For example explaining the meaning of variables,
typical values that can be used, possible problems to watch
for …. Use a good layout including blank lines, indentation
on lines etc.

7
EXAMPLE CODE:
% pl_inout
% P.Langston 2009-07-13
% Introductory example illustrating:
% input, output, simple calculation, comments, layout

% comments used here to explain Matlab - not necessary normally


% usually use to explain what code does,
% eg what variable names stand for, mathematical model used...

clear all % clears all variables in workspace


clc % clears window
format short % restores short output for floating point variables

% example with input defined in file, calculation, simple output


A = 3.2; % use semi-colon to suppress output
B = 1.9;
C1=A*B

clear all
% example with vector and more refined output
A = [3.2 5.1 -5.002];
B = 1.9;
C2=A.*B; % note syntax
disp(' C2 = ')
disp(C2)

clear all
% example with interactive input vector and further output
A=input(' Please enter vector A');
B = [9.11 8.7 3.5];
C=A+B;
Cout=strcat(' Total C = ',num2str(C));
%num2str : converts a number to a string - use help to get more info
% use help to find out more on function strcat
disp( Cout)

% example with string variables and date - see previous Hello.m

% example calculation of circle areas


rad = [3.2 5.1 4.3]; % radii of circles (choose suitable variable
names)
Area = pi.*rad.^2; % note pi is a Matlab constant
Rout=strcat(' Circle radii = ',num2str(rad));
disp(Rout)
Aout=strcat(' Circle areas = ',num2str(Area));
disp(Aout)
disp(' ')
disp(' example of format command')
format long
Area

who % lists active variables

8
As ever when working with computers when typing in files, m-files here,
save your work regularly. Matlab also creates .asv files (auto save files) as
back-ups.

Session 1 Exercises

1. Compute 5*(8/10) 1.04 + 4.15 - 5.078*87

2. Assign the following variables: p = 7.1, x = 4.92, k = -1.7 and evaluate


k
 1 
t = 
 1 + px 
3-4 omitted

5. Evaluate the following at x = 0.1 and a = 0.5

y= e( −π x ) − sin( x) / cosh(a ) − ln e ( x + a)

6. Write a script to perform the following calculations and save as Ques1_6.m.

10   2 
A = [1 2 3 4 5]; B = [2 4 6 8 10]; C =  20  ; D =  3.5  ;
  
 30  sin(π / 2) 
16 5   0.1 0.4 
E=  ; F= ;
 7 2 0.3 0.8

Y = A+ B X =C−D
P = 3.* A Q = sqrt (C ) R = sin( D)
Z1 = E.* F Z2 = E*F Z 3 = A./ B Z 4 = A. ^ 2

7. Determine the roots of

a) 4x2 + 3x = 25
b) x4 + 3x2 = 10

8. Solve the following set of equations:

a) 6x + 12y + 4z = 70
7x - 2y + 3z = 5
2x + 8y – 9z = 64

9
9. Write a script M- file that converts a user input temperature in Fahrenheit to
Celcius and displays the result. Check your script with the following data: [72 68 75
77 83 79].

10. ‘A cylindrical vessel has a diameter of 9 m and is 13 m high. It is to be replaced.


15% additional storage space is required, but there is no room to increase the
diameter beyond 9.2m. How much height needs to be added?’
Change the script so that it works for any volume change a user specifies on being
prompted.

I have coded these in an m-file. Output from program below:

>> palsession1
session 1 prog----------------------
q1---------------------------------

ans =

ans =

-436.5960

q2---------------------------------

t =

440.8779

q5----------------------------------------

y =

1.0736

q6--------------------------------------

Y =

3 6 9 12 15

X =

8.0000
16.5000
29.0000

P =

3 6 9 12 15

Q =

3.1623
4.4721
5.4772

R =

0.9093
-0.3508

10
0.8415

Z1 =

1.6000 2.0000
2.1000 1.6000

Z2 =

3.1000 10.4000
1.3000 4.4000

Z3 =

0.5000 0.5000 0.5000 0.5000 0.5000

Z4 =

1 4 9 16 25

Z2col: 1 2
3.1000 10.4000
1.3000 4.4000

q7-------------------------

ans =

-2.9030
2.1530

ans =

0 + 2.2361i
0 - 2.2361i
1.4142
-1.4142

q8-------------------------

x =

3
5
-2

q9-----------------------
TC:
22.2222
20.0000
23.8889
25.0000
28.3333
26.1111

q10-------------------------

dh =

1.3071

11
SESSION 2

2.1 Relational Operators

MATLAB has 6 relational operators to make comparisons between arrays:

Relational Operator Meaning


< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to

A value of 1 is assigned if statement is true; 0 is assigned if false. Combines with


find to analyse data in two arrays. The function find(x) returns the indices (not the
values) of the non-zero elements of the array x. Alternatively, x may be a relational
or logical expression.

2.2 Logical Operators

Logical Operator Meaning


& And
| Or
~ Not

2.3 Program Flow Control

Program flow control is done by branching or looping.

Branching – using the if and switch statements


Looping – using either the for or the while statements

2.4 Branching

The general form of the if statement is

if conditions #1
expressions #1
elseif condition #2
expressions #2
else
expressions #3
end

The statements elseif and else are optional and there can be more than one elseif
statement.

12
The switch structure is, essentially, an alternative to using the if statements. The
general form of the switch statement is

switch switch_expression
case case_expression #1
statements #1
case case_expression #2
statements #2
….
case case_expression #n
statements #n
otherwise
statements #n+1
end

2.5 Looping

A for loop repeats a series of statements a specific number of times. It takes the
following general form:

for variable = expression


statements
end

A while loop repeats one or more statements an indefinite number of times, leaving
the loop only when a specified condition has been satisfied. It takes the following
general form:

while condition
statements
end

2.6 User-Defined Functions

The second type of M-file is a function file. All the variables in a function file are
local, which means their values are only available within the function. A MATLAB
function file has the following general form:

function [OutputVariable] = FunctionName(Input Variables)


% Comments
Expression(s)

The first line is called the function definition line that has a list of inputs and output.

Sometimes, the number of variables transferred to a function is large. An alternative


is to create access to global variables for use by various functions using global.

13
Example from help system, copied from first part of help file:

for
Execute block of code specified number of times

Syntax
for x=initval:endval, statements, end
for x=initval:stepval:endval, statements, end

Description
for x=initval:endval, statements, end repeatedly executes one or more
MATLAB statements in a loop. Loop counter variable x is initialized to value initval
at the start of the first pass through the loop, and automatically increments by 1 each time
through the loop. The program makes repeated passes through statements until either x
has incremented to the value endval, or MATLAB encounters a break, or return
instruction, thus forcing an immediately exit of the loop. If MATLAB encounters a
continue statement in the loop code, it immediately exits the current pass at the location
of the continue statement, skipping any remaining code in that pass, and begins another
pass at the start of the loop statements with the value of the loop counter incremented
by one.

The values initval and endval must be real numbers or arrays of real numbers, or can
also be calls to functions that return the same. The value assigned to x is often used in the
code within the loop, however it is recommended that you do not assign to x in the loop
code.

14
EXAMPLE OF A FUNCTION M-FILE:

function h=pyt(a,b)
% pyt uses Pythagorous theorem to calculate hypoteneuse
% of a right angled triangle from other lengths input

h = sqrt(a.^2+b.^2);

In command window:

>> clear all


>> g=pyt(3,4)

g =

>> a=[3 7.1 9.2];


>> b=[4 5.1 3.3];
>> c=pyt(a,b);
>> z= [a' b' c']

z =

3.0000 4.0000 5.0000


7.1000 5.1000 8.7419
9.2000 3.3000 9.7739

>>

15
EXAMPLE M FILE

% HI_LO
% Computer generates random number between 0 and 100
% You have 7 guesses, The computer tells you if you
% are too high or too low
% Adapted from Biran & Breiner
% Aug 2008 P. Langston

x=fix(100*rand); % gets an integer value


ntot=7; % assigns number of guesses allowed
nused=0;

for k=1:ntot
nleft=int2str(ntot-nused);
disp(['You have ' nleft ' guesses left'])
guess = input(' enter guess ')
if guess < x
disp('Low')
elseif guess > x
disp('High')
else
disp('You won')
return
end
nused=nused+1; % increments number of used guesses
end

disp('You lost')

16
The following code will do the same but it is not so good.
Why?

x=fix(100*rand)
nused=0;
for k=1:7
nleft=int2str(7-nused);
disp(['You have ' nleft ' guesses left'])
guess = input(' enter guess ')
if guess < x
disp('Low')
elseif guess > x
disp('High')
else
disp('You won')
return
end
nused=nused+1;
end
disp('You lost')

17
EXAMPLE M-File and Function M-File

% PLsepdist
% Exercise H82CSY P. Langston July 2009
% use of: if, for loop, logical variable, user defined function
% calculate distance between points and output warning message if
% any two points close (say aircraft at a certain altitude, units km)

clear all
clc

% data: positions of points


x=[5 3.1 4 -7 9 0 2.1 2.2];
y=[4 2.1 9 -3 9 5 6.1 6.2];

sep_close=1.0; % a warning displayed when separation less than this

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

Np=length(x); % get number of points


iclose=false; % initialise logical variable

for i=1:Np-1
for j=i+1: Np % this tests all pairs of points
sep=dist(x(i), y(i), x(j), y(j));
if( sep < sep_close)
iclose=true;
disp([' points ',num2str(i), ' ',num2str(j), ' too close'] )
disp([' separation = ',num2str(sep), ' km '] )
end
end
end

if(iclose==false)
disp(' all points at safe separation')
end

function d=dist(x1,y1,x2,y2)
% dist calculates dstance between 2 points in 2D
% x, y co-ords input
% P. Langston July 2009

dx=x2-x1;
dy=y2-y1;
d = sqrt(dx.^2+dy.^2);

Displayed in workspace

points 7 8 too close


separation = 0.14142 km
>>

18
Session 2 Exercises

1. Write a script to output the K value corresponding to the pipe fitting input. Use
switch (and the help system if necessary).

Fittings K value
45 deg elbow 0.3
90 deg square elbow 1.2
gate valve: fully open 0.15
globe valve 3.6

2. Moved to later section

3. If you deposit £200 in a bank account paying 3% annual interest, what will your
savings be after 15 years? How long will it take to accumulate £5000?
(£311.59 105.9 yr) NB What format should you use for output?

RT
4. The ideal gas law is given by P= . A more accurate gas law is the van der

RT a
Waals equation: P= − 2
Vˆ − b Vˆ
a
where the term b is a correction for the volume of the molecules, and the term
Vˆ 2
is a correction for molecular attractions. The values of a and b depend on the type of
gas. For chlorine, if R=0.08206 L atm/mol K, a = 6.49 and b = 0.0562 in these
units. Write a function M-file to compute pressure using the van der Waals equation
for chlorine. (T=298 K, P=1.0815 atm, Pideal = 1.0917 atm)

5.
% PLsort
% Exercise H82CSY P. Langston September 2008
% sorting and summing

% data
A=[5 3.1 4 -7 9 0 2.1];

A=sort(A, 'descend'); % see help for more info

A'

B=sum(A)

% As an exercise see if you can write code to do this without using


% a Matlab function
%----------------------------------------------------------------------

A=[5 3.1 4 -7 9 0 2.1]; % reset A

19
SESSION 3

3.1 Plotting Functions

The simplest plotting function is for an x-y plot. It is a graphical representation of a


function for a defined data range, e.g. x = [ : : ]; y=f(x); plot (x,y). Note that y
does not need to be a function of x, it could contain an array of numerical values
which is the same size as x.

A number of commands specify the appearance of the plot including title, xlabel,
ylabel, axis and grid but it is often simpler to edit a plot once it has been created.

title(‘text’)
xlabel(‘text’)
ylabel(‘text’)
axis ([xmin xmax ymin ymax])

The function fplot('string', [xmin xmax]) allows MATLAB to decide how many data
points are needed to represent the function within the limits given.

For polynomials, the polyval function requires merely the coefficients p to be


specified, as in plot(x,polyval(p,x)).

There are more sophisticated ways of achieving multiple curves in the same figure,
but the simplest is to issue the hold on command after the first plot, all subsequent
plots will go into the same figure until hold off is issued.

To fit more than one graph into one figure the subplot(m,n,p) command preceeds
the plot(x,y) command. m is the number of rows, n the number of columns and p
the position of the graph counting from the top left-hand corner, e.g. after
subplot(2,2,4) the figure window is split to accommodate 4 graphs and currently the
bottom right one is plotted.

A few variations of the x-y plot are:

bar(x,y)
loglog(x,y)
semilogx(x,y) and semilogy(x,y)
plotyy(x1,y1,x2,y2) adding a second y-axis

3.2 Regression

MATLAB performs a least squares regression on two dependent data sets x and y at
the polyfit(x,y,n) command, where n is the polynomial coefficient (i.e. 1 for linear,
2 for quadratic etc.). Although with the current editions it is much easier to just plot
the data and then use the Basic Fitting tool.

3-D Plots (line, mesh(surface) and contour) are not covered here, but as they are
widely believed to be the most entertaining feature of MATLAB, have a look at a few
examples in MATLAB Help > Demo > Graphics.

20
3.3 Interpolation

Input data is often tabulated property data (e.g. steam tables), which makes
interpolation necessary; linear interpolation is provided by interp1 for one
dimension and interp2 for 2.

If x contains the independent, and y the dependent variables, and x_int the
intermediate x values for which y is to be interpolated, then interp1(x,y,x_int)
gives the desired y values. Similarly, if z is dependent on x and y,
interp2(x,y,z,x_int,y_int) gives the desired z value.

3.4 Numerical Integration

There are three functions available to evaluate integrals numerically:


trapz(x,y) performs trapezoidal integration and takes arrays of numbers
quad('function',a,b,tol) uses Simpson's rule and quadl('function',a,b,tol) uses
Lobatto quadrature. a and b stand for the lower and upper limits, tol is optional and
specifies the tolerance for error. Both quad functions require a function and cannot
accept arrays directly, but they can accept user-defined functions.

3.5 Numerical Differentiation

The function d=diff(x) can be made use of to perform simple numerical


differentiation. For x=[x1,x2,x3, …..], it returns d=[x2-x1,x3-x2, …..]. So, dy/dx can
be represented as diff(y)./diff(x) as a 'backwards difference' approximation. The
derivatives of polynomials can also be determined directly with the specific polyder
function.

3.6 Data and Variable Types

To investigate the different types of variables (local, global..) search on:


types of variables
in the help search.

For the types of data (integer, real, character string…)search on:


data types

21
Session 3 Exercises

1. a) Plot the functions i) y = 4 6x +1


ii) z = 5e0.3 x − 2 x
iii) w = cos( x )
2

on the same figure and check for singularities.

b) Evaluate the integrals for the functions in a) between 0 and 2.


( 20.3804, 9.7030, 0.4640)

2. Plot the following polynomial over the range -6 ≤ x ≤ 6 with a spacing of 0.01.
3x5 + 2x4 -100x3 + 2x2 -7x + 90

3. Write a function M-file that returns the saturation temperature for any input
pressure between 1 and 20 bar using the data below taken from the steam tables. A
warning should appear if the input pressure is outside the specified range.

P/kP 100 300 500 700 900 1100 1300 1500 1700 1900 2200
a
Ts/ C 99.63 133.54 151.85 164.96 175.36 184.06 191.6 198.28 204.3 209.79 217.24

Check on the assumption that linear interpolation is adequate by plotting the data.

4. For the data in question 3, does a regression with a higher polynomial coefficient
give a better fit?

22
COMMAND SUMMARY

Some useful commands in Matlab which can be issued at the >> prompt are:

cd Z: changes to network Z: drive


dir lists files in current directory
save <filename> saves workspace to file <filename.mat> in current directory
load <filename> loads workspace from file <filename.mat> in current directory
who list names of matrices/variables in work-space
clear B C erase matrices B and C from work-space
size(A) return the size of matrix A (rows and columns)
plot(x,y) produce x-y plot for points in vector y against vector x
title(‘Graph plot’) writes title as header on plot
xlabel(‘x/seconds’) writes x-axis label on plot
ylabel(‘y/metres’) writes y-axis label on plot
help <name> provide on-line help on a Matlab function called <name>
exit exit from Matlab

A=[1 2 3; 4 5 6; 1 3 5] Assigns data to a 3x3 matrix A


B=A(1:3,1:2) creates matrix B as a 3x2 submatrix of A
C=B’ assign transpose of matrix B to C
y=[4;6] creates column vector y
x=B*y matrix/vector multiply
z=inv(A)*x multiplication involving inverse of A (to solve Ax=z for z given x)
A=zeros(3,3) assign a 3x3 matrix of zeros to A
B=eye(3,3) assign the 3x3 unit matrix I to B
y2=interp1(x,y,2) interpolate for the value of y at x=2 amongst the data in x,y
xm=max(x) assign the maximum value of data in vector x to xm

ans is an auxiliary matrix containing the result of the last unassigned command. Files
containing Matlab commands that can be run from a current directory by simply typing
their name at the Matlab prompt have the .m file extension. Files containing matrices
which can be loaded directly into the workspace using the ‘load’ command have the .mat
file extension.

General advice in programming any language

Start simple, test, and build it up as you go along.


Keep it general.
Comments and layout are important.
Use debugging tools to test the code.
Documentation and management are important in larger systems.

23
More Advanced Section

This section goes beyond the module requirements and what is needed for the
coursework and class test. I have included it for people who are interested. If you are
having problems here omit this section.

1. Write a script to play a game of “paper, scissors, stone”. (See example of number
guessing game HI_LO.)

2. Investigate 3D graphics. Draw a view of some spherical particles of different sizes.


See the help file for the following commands: sphere, surf, axis, light, shading, hold,
whitebg

3.7 Solution of Differential Equations

MATLAB has a number of solvers for ordinary differential equations (ODEs), which we
are not covering here. It is worth being aware of them though, as they form the
backbone of the integrator operations in Simulink.

ODE Solvers:
ode45 Nonstiff differential equations Runge-Kutta
ode23 Nonstiff differential equations Runge-Kutta
ode113 Nonstiff differential equations Adams
ode15s Stiff differential equations and DAEs NDFs (BDFs)
ode23s Stiff differential equations Rosenbrock
ode23t Moderately stiff differential equations and DAEs Trapezoidal rule
ode23tb Stiff differential equations TR-BDF2

24

You might also like