Professional Documents
Culture Documents
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.
PROGRAM: (software) Series of executable expressions often hidden from user (eg
Hysys, Word, Windows XP)
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.
1
Why learn Matlab Programming?
Note we will not be doing any CFD in this module but the principles here are
generally relevant in any scientific programming.
“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
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.
A semicolon (;) at the end of an expression suppresses the answer being printed on
screen.
↑ recalls previous lines (useful for editing out errors)
3
1.2 MATLAB Built-In Functions
Mathematical Constants π pi
∞ inf
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
4
1.4 Arrays and Matrices
The two classes of arrays that are commonly encountered in MATLAB are numeric
and character. For numeric arrays:
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.
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.
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
5
Matrices can be used to solve simultaneous equations. Consider the following system
of n equations and n unknowns:
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
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.
The format function can be used to control the output format of numeric information
to the command window. Use the help system to investigate.
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
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
>>
7
EXAMPLE CODE:
% pl_inout
% P.Langston 2009-07-13
% Introductory example illustrating:
% input, output, simple calculation, comments, layout
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)
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
y= e( −π x ) − sin( x) / cosh(a ) − ln e ( x + a)
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
a) 4x2 + 3x = 25
b) x4 + 3x2 = 10
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].
>> 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 =
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.4 Branching
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:
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
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:
The first line is called the function definition line that has a list of inputs and output.
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:
g =
z =
>>
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
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
%----------------------------------------------------------------------
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
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
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
Vˆ
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'
B=sum(A)
19
SESSION 3
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.
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.
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.
21
Session 3 Exercises
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:
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.
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.)
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