You are on page 1of 18

ESG

111
Numerical Methods for
Chemical Engineering Analysis
WEEK 3-2
Introduction to MATLAB Programming


Maya K Endoh

File I/O: load and save


There are 3 modes (or opera6ons) on les:
read from
write to (assumes from the beginning)
append to (wri6ng to, but star6ng at the end)

save and load func6on (simple le I/O


commands)
save: for saving a matrix to a le
load: reading from a le into a matrix
simple le type for save/load is data (.dat) or text
(.txt) le

Reading, Wri1ng, Appending


To read from a le into a matrix variable:
.ext would be .dat or .txt
load lename.ext
Note: this will create a matrix variable named lename (same
as the name of the le but not including the extension on the le
name)
This can only be used if the le has the same number of values
on every line in the le; every line is read into a row in the
matrix variable
-ascii is used to
To write the contents of a matrix variable to a le:
create .dat or .txt le
save lename matrixvariablename ascii
save command will overwrite the le, if the le already exists
To append the contents of a matrix variable to an exis1ng le:
-append is used to
save lename matrixvariablename ascii -append append the data of
matrixvariablename to
matrix dimension should be same as the original data
the exis6ng data of
lename

EX) using load and plot


A le data1.txt stores the lm thickness of
10 samples.
1. Load the data and plot the graph from Command
Window
2. Write the script which will read from this le,
round the thickness in 1 decimal, and plot with
red *s:

Example Solu6on
(in Command Window)
*load creates data matrix named data1 in Command Window*
>> load data1.txt
>> data1
data1 =
1.0000
33.5100
2.0000
34.4200
3.0000
35.9000
4.0000
35.1100
5.0000
34.9900
6.0000
34.2500
7.0000
33.6700
8.0000
35.1300
9.0000
34.1900
10.0000
34.6200

>> x=data1(:,1);
>> y=data1(:,2);
>>
>>
>>
>>

plot(x,y,'r*')
xlabel('sample')
ylabel('thickness / nm')
title ('film thickness')

Example Solu6on
(in Script Window)
%load and plot from external data
load data1.txt
x=data1(:,1) ;
y=data1(:,2 );
y=round(y,1);
plot(x,y, 'r*')
xlabel('sample')
ylabel('thickness / nm)
title('film thickness)
axis([0 11 33 36])

User-Dened Func6ons: M-le func1on


User-Dened Func6ons are func6ons that you
write
Simple dened func6on: calculates and returns
one value
Func6on is stored in an M-le (M-le func6on)
M-le func6on works just like using a built-in
func6on:
1. Call it by giving the func6on name and passing
argument(s) to it in parentheses
2. the func6on uses the argument(s) to calculate the
result
3. Returned and display the result

General Form of Func6on


Deni6on

The func6on deni6on would be in a le fnname.m:


fnname.m
func6on
header

The name of the output argument followed by the assignment operator,=

function outarg = fnname(input arguments)


% Block comment

func6on
body

Statements here;
outarg = some value;

Name of the func6on should be the same


as that of M-le
Will be printed when help is used
Must put a value in the output
argument

end
End of the func6on

Func6on header
1

1.
2.
3.
4.
5.

func1on outarg = fnname(input arguments)


The header always starts with the reserved word
func1on
Next is the name of an output argument, followed by
the assignment operator
The assignment operator is followed
The func6on name fnname should be the same as
the name of the m-le in which this is stored
The input arguments correspond one-to-one with the
values that are passed to the func6on when called

Passing Mul6ple Arguments


For Example, passing the two arguments in the func6on,
Input two arguments in the func6on header
Two values must be passed to the func6on
The order of input needs to be considered!
1st value is stored in the 1st input argument, so as 2nd value.
function outarg = fnname(x,y)
outarg = a*x/y

Output argument should have two values

Func6on Example
For example, a func6on that calculates and returns the volume of a
circle
There would be one input argument: the radius
There would be one output argument: the volume
In an M-le called fn_volume.m:
func6on volume=fn_volume(radius)
% This func6on calculates the volume of a sphere
volume = 4*pi/3*(radius^3);
end

Func6on name same as the M-le name


Pueng a value in the output argument is how the func6on returns
the value; in this case, with an assignment statement (Note:
suppress the output)
The names of the input and output arguments follow the same rules
as variables, and should be mnemonic

Calling the Func6on


This func6on could be called in several ways:
>> fn_volume(4)
- This would store the result in the default variable ans

>> myvol = fn_volume(9)


- This would store the result in the variable myarea
- A variable with the same name as the output argument could also be
used

>> disp(fn_volume(5))
>> fprinh(The volume is %.1f\n, fn_volume(5))
- disp and fprinE would display the result, but it would not be stored
for later use

Passing arrays to func6ons


mul6ple input arguments can be passed to a func6on
the operator should be changed to array operator,
such as .^
volume = 4*pi/3*(radius.^3)
volume = 4*pi/3*(radius^3)
arrays could not be passed to this func6on as it is

To x that, change to the array mul6plica6on operator .^


func6on volume=fn_volume(radius)
% This func6on calculates the volume of a sphere
volume = 4*pi/3*(radius.^3);
end

a vector could be passed to the input argument radius

Calling a M-le func6on from a Script


A func6on can be called from a script)

General Form of Simple Program


script.m
Get input
Call fn to calculate result
Print result

fn.m
func6on out = fn(in)
out = value based on in;
end

This combina6on of a script (stored in an Mle) and the func6on(s) (also stored in Mles) that it calls is a program

a func6on returns a value


BUT does NOT normally
print the value

Example
volume_calculate.m
%This script calculates the volume of a sphere
%prompts the user for the radius
radius=input('Please enter the radius: ');
%calls out fn_volume function
vol=fn_volume(radius);
fprintf('For a sphere with a radius of %.2f,',radius)
fprintf(' the area is %.2f\n',vol)
fn_volume.m
function volume=fn_volume(radius)
%This function calculates the volume of a sphere
volume = 4*pi/3*(radius^3);
end

Func6on with Local Variables


Variables that are used within a func6on are
called local variables
Calcula6on in a func6on may require the use
of extra variable (local variable) within the
func6on
Local variables are normally NOT displayed

Introduc6on to scope
The scope of variables is where they are valid
The Command Window uses a workspace called the
base workspace
Scripts also use the base workspace
This means that variables created in the Command
Window can be used in a script and vice versa (this is
a bad idea, however)
Func6ons have their own workspaces so local
variables in func6ons, input arguments, and output
arguments only exist while the func6on is execu6ng

Exercise
The volume of a hollow sphere is given by
4/3 (Ro3 Ri3) where Ro is the outer radius and Ri
is the inner radius
1. Write the func6on which calculates the volume
of a hollow sphere in M-le.
2. Write a script that will prompt the user for the
radii, call a func6on that will calculate the
volume, and print the result.

You might also like