Professional Documents
Culture Documents
111
Numerical Methods for
Chemical Engineering Analysis
WEEK 3-2
Introduction to MATLAB Programming
Maya K Endoh
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])
func6on
body
Statements here;
outarg = some value;
end
End of the func6on
Func6on header
1
1.
2.
3.
4.
5.
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
>> 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
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
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
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.