You are on page 1of 30

Scripts and Functions

Scripts
Introduction
MATLAB scripts are also known as macros, programs,
code, or m.files. They are simply a collection of
commands, the code is constructed in the m.files
editing window which is a text editor. An m.file is
therefore a simple ASCII text file.
When creating an m.file each line should be entered as
if you were entering it at the command prompt in the
command window.
When you finish entering your work, save it in your
folder or your disk by giving it an appropriate name,
MATLAB will append an extension of .m in order for it
to recognize the file as an m.file. Use comment lines to
make your work more understandable, add % at the
beginning of a comment line, matlab will ignore it.
Macros, also known as Scripts are simple
subset of functions and only use functions.
They are just a listing of commands which
could have been entered in the command
prompt, one after another.
Functions files are special kinds of Scripts but
can have input and output arguments. They
allow you to define your own functions.
The first line of a function file must start with
the word Function and followed by the output
arguments then = and functionname then
input arguments in brackets. For example;
Function (y-out) = function-name(x-in)
Where y-out is a single output and x-in is a
single input. You can also have multiple
outputs and inputs.
Function-name is also the name of the m.file.
To create a script/m.file, click File, then New,
then M-file. A new window will appear called
the Editor. To create a new script, simply type
the sequence of statements.
For example, a Script file that converts
temperature in Celsius into oF and then into oR
from 0 100 at interval of 15 and displays
results could be as follows;
% Conversion of temperature from tc to tf and tr
% tc is temperature in Celsius, tf is temp in deg F,
% and tr is temp in deg Rankine
tc = [0:15:100];
tf = 1.8.*tc + 32;
tr = tf + 460;
% Combine answer into one
T = [tc;tf;tr]
Save this file in a directory of your choice and call
it any name, e.g. temcon
There are two ways to view a script once it has
been written: either open the Editor Window
to view it, or use the type command at the
command prompt to view it in the Command
Window.
To run the script, the name of the file is typed
at the command prompt (without the .m
extension).
Example (1) of a Script file could be something
like this:
Theta = linspace(1.6,4.6);
Tandata = tan(theta);
Plot(theta,tandata);
Xlabel(\theta (radians));
Ylabel(tan(\theta));
Grid on; Save the file as tanplot

Dr. A. Okullo 8
Save this file in a directory of your choice and call
it any name, e.g. tanplot.m. To run this file you
must be in the directory where you saved it. You
run the file by typing its name at the command
prompt, e.g.
>> tanplot
Example 2 of script file
Trapezoid rule for integral of x^2 between 0 and 1
h = 0.1;
x = [0:h:1];

Dr. A. Okullo 9
Lenx = length(x); y = x.^2;
Int = (h/2)*(y(1) + 2 * sum(y(2):(lenx-1))) + y(lenx);
Save as trapint.m
At the prompt call trapint. Give mesh size h = 0.1 then
Enter
Example (3) Script file
Generating noise data
X = 0:0.025:2; Y = sin(pi*x);
Yn = y + 0.25*(rand(size(x)-0.5);
Plot(x,y,- -,x,yn,-)
Title([dashed line: sin(pi*x), sold line : noisy data])
Xlabel(noise is random from[-1/8, 1/8])
Save it as noisedat and try by running it at the prompt.

Dr. A. Okullo 10
Example 4 script file: generating noisy data
X = 0:0.025:2;
Y = sin(pi*x);
Yn = y + 0.25* (rand(size(x) 0.5));
Plot(x,y,,x,yn,-)
Title(Dashed line is sin(pi*x), Solid line is noisy
data)
Xlabel(noise is random from -1/8 to 1/8)
Save it as noisedat.m. Run it from the prompt.
Dr. A. Okullo 11
Functions files combined with some in-built
MATLAB commands
Finding the zero/root of a function
with fzero command
Example 1. Find the zero of a function y(x) =
sin(x) closest to x=3 using the fzero function.
This can be typed directly into the command
prompt.
X = fzero(sin(x),3)
Ans = 3.1416
This is the zero of sin(x) closest to the initial
guess of 3.
Example 2.
Solve the system of linear equation given
below:
3.5u + 2v =5
-1.5u + 2.8v + 1.9w = -1
-2.5v +3w = 2
This also can be entered directly in to the
command window but first clear all
A = [3,5 2 0; -1.5 2.8 1.9; 0 -2.5 3];
B = [5 -1 2];
M = A\B
M=
1.4421 this is u
-0.0236 this is v
0.6470 this is w
The command A\B performs the reverse matrix division.
() transposes matrix B which is required to perform
matrix division.
The matrix is in the form Ax = B, so A\B is like dividing
out the values of x. alternatively one can use b/a for
the same
Solving linear and non-linear eqns.
You can use fzero to solve a single non-linear
eqn. for a system of non-linear equation, use
fsolve.
Fsolve function is most useful for simple
chemical engineering problems. It is a numeric
solver for solving system of non-linear
continuous equations.
For systems of n continuous equations (f1 ----
fn) with n unknown variables (x1-----xn) given
by;
F(1)= f1(x1, x2, x3, xn) = 0
F(2) = f2(x1, x2, x3, ..xn) = 0
F(3) = f3(x1, x2, x3, ..xn) = 0
..
F(n) = fn(x1, x2, x3, ..xn) = 0
This solver can be used to determine the
unknown variables x1, through xn.
Example 3. Solve the system of equations below
using fsolve.
2a b e-a = 0
2b a e-b = 0
The most efficient way to solve this is to create an
m.file.
Function f = myex(x)
f = [2*x(1)-x(2)-exp(-x(1); -x(1)+2*x(2)-exp(-x(2))];
Now return to the command prompt and use
fsolve
>>x0 = [-5 -5] % initial guess (arbitrary)
>>fsolve(myex, xo, optimset(fsolve))
Optimization terminated successfully: .
Ans
0.5671 0.5671
a b
Example 4
Solve x2 2x = 0
Function Res = Myfun(x)
Res = x^2 2 * x
End
At the prompt enter: A = fzero(Myfun,-5)
Example 5
Find the root of the function y = x2 -1 + x 1
Function Y = Root(x)
Y = x^2 1 + x 1
End
At the prompt type Z = fzero(Root,3)
Ans: Z = 0.618
Try this with the sin(x) function with the initial
guess = 3.
Symbolic Integration and
Differentiation
MATLAB has the ability to perform symbolic
integration and differentiation, thanks to
Maple engine located in the symbolic toolbox.
Matlab can solve differential equations
symbolically providing general or a unique
solutions. diff is used for symbolic
differentiation and int for symbolic
integration.
Example 6. integrate ax2 +b with respect to x
where a and b are constants.
First the symbolic variables in the expression
must be defined using syms command. These are
a, b and x in this expression.
>> syms a b x
>> diff(a*x^2+b*x)
Ans
2*a*x+b
Now use int to reverse it to its original state
>>int(2*a*x+b)
Ans
a*x^2+b*x or x*(b+a*x)
Matlab can also solve ordinary differential
equation symbolically with or without boundary
conditions or initial parameters. The dsolve
command is used for this. The letter Dij is used to
indicate a derivative where (i) is the order of
differentiation and (j) is the dependent variable.
D specifies first order derivative and D2
second order and so on. The letter (t) is
default independent variable for dsolve. So
D2y is d2y/dt2
Example 7. Solve the ode d2y/dx = 6y-dy/dx
where y(x) using dsolve.
>> dsolve(D2y=6*y-Dy,x)
Ans
C1*exp(-3*x)+C2*exp(2*x) =>C2e2x+C1/e3x
Example 8 Solve the d2m/dx2 + m =0, m(0) = 2
and dm/dx(0) = 3, where m(x).
>>dsolve(D2m+m=0,m(0)=2,Dm(0)=3,x)
Ans
3*sin(x)+2*cos(x)
Numerical solutions to differential equations.
These ones use m.files mostly. Refer to problems
of fluid flowing into large tank, consecutive
reactions A B C, etc.
Higher order ODEs
To solve higher order odes in matlab, they must
be converted in to a system of first orders odes,
for example, an ode can be written like
Dy/dx = f(x,y, y, y, y, .yn-1)
Can also be written as a system of first order;
Y1 = y; y2 = y; y3= y,yn = yn-1
Then it can be represented as
Y1 = y2; y2 = y3; yn-1 = yn
Example 9. Solve the following differential
equation by converting it to a system of first
order;
Y + Y + Y = 0; Y(0) = 1; Y(0) = 0
First conversion
Y = y1 = y(1); Y =y2 = y(2)
Then write it as first order
Y = y(1)
dY/dt = Y = y(2)
d2Y/dt2 = Y = -(y(2)+y(1))
Create an m.file now to solve this system
function dmdt = ex6(t,y)
dY/dt = y(2);
dY2dt = -(y(2)+y(1));
dmdt = [dYdt; dY2dt];
At the prompt
tspan [0 10];
y0 [1 0]
[t,Y] = ode45(ex6, tspan,yo);
plot(t,Y(:,1),+,t,Y(:,2))
legend(Y and dY/dt)
xlabel(t); ylabel(Y and dY/dt)

You might also like