MATLAB Functions and Files
Cheng-Liang Chen
PSE
LABORATORY
Department of Chemical Engineering National TAIWAN University
Chen CL
1
Using Files
filename1.m Used for MATLAB programs and for some MATLAB functions M-files are ASCII (American Standard Code for Information Interchange) files that are written in the MATLAB language (Can be created using any word processor or text editor )
filename2.mat
Used to save the names and values of variables created during a MATLAB session MAT MA T-files are binary are binary files files (more compact storage than ASCII ASCII files) files)
⇒ readable only by the software that created them
ASCII Data Files Header: Header: co comm mmen ents ts de desc scri ribi bing ng wh what at th thee da data ta re rep pre rese sent nts, s, th thee da date te it was created, who created the data . . . One or more lines of data
Chen CL
1
Using Files
filename1.m Used for MATLAB programs and for some MATLAB functions M-files are ASCII (American Standard Code for Information Interchange) files that are written in the MATLAB language (Can be created using any word processor or text editor )
filename2.mat
Used to save the names and values of variables created during a MATLAB session MAT MA T-files are binary are binary files files (more compact storage than ASCII ASCII files) files)
⇒ readable only by the software that created them
ASCII Data Files Header: Header: co comm mmen ents ts de desc scri ribi bing ng wh what at th thee da data ta re rep pre rese sent nts, s, th thee da date te it was created, who created the data . . . One or more lines of data
Chen CL
2
Controlling Input and Output speed = 63; disp di sp(’ (’Th The e pr pred edic icte ted d sp spee eed d is is:’ :’) ) disp(speed) The Th e pred predic icte ted d sp spee eed d is is: : 63
Chen CL
3
Input/Output Commands Command
Description
disp(A)
Displays the contents, but not the name, of the array A.
disp(’text’)
Displays the text string enclosed within single quotes.
format
Controls the screen’s output display format (Table3.3-2).
fprintf
Performs formatted writes to the screen or to a file (see Appendix C).
x=input(’text’)
Displays the text in quotes, waits for user input from the keyboard, and stores the value in x.
x=input(’text’,’s’) Displays the text in quotes, waits for user input from the keyboard, and stores the input as a string in x. k=menu(’title’,’option1’,’option2’,...) Displays a menu whose title is in the string variable ’ title’, and whose choices are ’option1’,’option2’,. . .
Chen CL
4
Ex: Design of A Parallel-plate Capacitor Capacitors are widely used in electric circuits. A capacitor stores energy by maintaining the charge separation produced when a voltage is applied to the device. A parallel-plate capacitor is constructed from two or more parallel conducting plate, each having an area A and separated from each other by air or another dielectric material such as mica or paper. If the plates are separated by a distance d, the device’s capacitance C , which is a measure of its energy storage capacity, can be computed from the formula C = (n
− 1) Ad
where n is the number of plates and is the permittivity of the dielectric material . The unit of capacitance is the coulomb/volt and is called the farad (F). Suppose we use plates having an area A = 20 centimeters2, separated by a distance d = 4 millimeters with air, for which = 8.85
−12
× 10
farad/meter. Construct a table to
select the number of plates needed to obtain a desired capacitance value . Assume
that no more than 10 plates will be used.
Chen CL
5
Ex: Design of A Parallel-plate Capacitor % Program capacitor.m % Generates a table of capacitance values. % % Define the values of the constants. permittivity = 8.85e-12; A = 20/100^2; % Convert A to square meters No. Plates Capa.(F)xe12 d = 4/1000; % Convert d to meters 2.0000 4.4250 % 3.0000 8.8500 n = [2:10]; % Vector n is # of plates 4.0000 13.2750 % Generates capacitance values 5.0000 17.7000 % (Multiply by 10^12 for 6.0000 22.1250 % display purposes) 7.0000 26.5500 C = ((n-1)*permittivity*A/d)*1e12; 8.0000 30.9750 % 9.0000 35.4000 table(:,1) = n’; % Create first column 10.0000 39.8250 table(:,2) = C’; % Create second column % Display table heading % and table itself. disp(’No. Plates Capa.(F)xe12’) disp(table)
Chen CL
6
Numeric Display Formats Command
Description and Example
format short format long format short e format long e format bank format + format rat
Four decimal digits (the default); 13.6745 16 digits; 17.27484029463547 Five digits (four decimals) plus exponent; 6.3792e+03 16 digits (15 decimals) plus exponent; 6.379243784781294e-04 Two decimal digits; 126.73 Positive, negative, or zero; + Rational approximation; 43/7
format compact format loose
Suppresses some line feeds Resets to less compact display mode
Chen CL
7
User Input
The Input function displays text on the screen, waits for the user to enter something from the keyboard, and then stores the input in the specified variable x = input(’Please enter the value of x: ’) Calender = input(’Enter the day of the week: ’, ’s’) k = menu(’title’, ’option1’, ’option2’,...)
Demo the following in the class: k = menu(’Choose a data marker’, ’o’, ’*’,’x’); type = [’o’, ’*’,’x’]; x = [1,2,3,4]; y = [2,4,3,5]; plot(x,y, x,y, type(k),’LineWidth’,2,’MarkerSize’,3) set(gca,’LineWidth’,2,’FontSize’,16) title(’Test the use of menu’,’FontSize’,16)
Chen CL
8
Test Your Understanding T3.0-1 Write a script file to compute and display a table to convert from radians to degrees. Use five values for the radian angle: 1, 2, 3, 4, and 5 radians. Be sure to label each column in the table. T3.0-2 The volume V of a sphere depends on its radius r as follows: V = 4πr 3/3. Write a script file to compute and display a table showing the volume in cubic meters versus the radius in meters, for 1 r 2, in increments of 0.1. Label each column.
≤ ≤
T3.0-3 The surface area A of a sphere depends on its radius r as follows: A = 4πr 2. Write a script file that prompts the user to enter a radius, computes the surface area, and displays the result.
Chen CL
9
Some Common Mathematical Functions Exponential exp(x) sqrt(x) Logarithmic log(x) log10(x) Complex abs(x) angle(x) conj(x) imag(x) real(x) Numeric ceil(x) fix(x) round(x) sign(x)
Exponential; ex Square root; x
√
Natural logarithm; ln(x) Common (base 10) logarithm; log(x) = log 10(x) Absolute value; x Angle of a complex number x Complex conjugate Imaginary part of a complex number x Real part of a complex number x Round to the nearest integer toward Round to the nearest integer toward zero Round toward the nearest integer Sigmum function: +1 if x > 0; 0 if x = 0;
∞
−1 if x < 0
Chen CL
10
Complex Number Functions x = -3 + 4i; y = 6 - 8i; mag_x = abs(x)
angle_y = angle(y)
mag_x = 5.0000
angle_y = -0.9273
mag_y = abs(y)
sum_angles = angle_x + an
mag_y = 10.0000
sum_angles = 1.2870
mag_product = abs(x*y) angle_product = angle(x*y 50.0000 angle_product = angle_x = angle(x) 1.2870 angle_x = 2.2143
Chen CL
11
Test Your Understanding T3.1-1 For several values of x and y, confirm that ln(xy) = ln x + ln y. T3.1-2 Find the magnitude, angle, real part, and imaginary part of the number 2 + 6i.
√
Chen CL
12
Trigonometric Functions Trigonometric cos(x) cot(x) csc(x) sec(x) sin(x) tan(x) Inverse trigonometric acos(x) acot(x) acsc(x) asec(x) asin(x) atan(x) atan2(y,x)
Cosine; cos x Cotangent; cot x Cosecant; csc x Secant; sec x Sine; sin x Tangent; tan x Inverse cosine; cos 1x Inverse cotangent; cot 1x Inverse cosecant; csc 1x Inverse secant; sec 1x Inverse sine; sin 1x Inverse tangent; tan 1x Four-quadrant inverse tangent −
−
−
−
−
−
Chen CL
13
Test Your Understanding T3.1-3 For several values of x, confirm that eix = cos x + i sin x. T3.1-4 For several values of x in the range 0 sin 1 x + cos 1 x = π/2.
≤ x ≤ 2π, confirm that
T3.1-5 For several values of x in the range 0 tan(2x) = 2 tan x/(1 tan2 x).
≤ x ≤ 2π, confirm that
−
−
−
Chen CL
14
Hyperbolic functions Hyperbolic cosh(x) coth(x) csch(x)
Hyperbolic Cosine; cosh x = (ex + e x)/2 Hyperbolic Cotangent; cosh x/ sinh x Hyperbolic Cosecant; 1/ sinh x
sech(x) sinh(x)
Hyperbolic Secant; 1/ cosh x Hyperbolic Sine; sinh x = (ex
tanh(x)
Hyperbolic Tangent; sinh x/ cosh x
−
−e
x
−
)/2
Chen CL
15
Inverse Hyperbolic functions Inverse hyperbolic acosh(x)
Inverse hyperbolic cosine; cosh 1 x = ln(x + x2 1), x
√ −
−
acoth(x)
≥1
Inverse hyperbolic cotangent; coth 1 x = 21 ln( xx+11 ), x > 1 or x < Inverse hyperbolic cosecant; −
−
acsch(x)
−1
csch
asech(x)
−1
1
x2
+ 1, x = 0
x = ln( x1 +
1
x2
−1
tanh
− 1, 0 < x ≤ 1
Inverse hyperbolic sine; sinh 1 x = ln(x + x2 + 1), Inverse hyperbolic tangent; −
atanh(x)
x = ln( x +
Inverse hyperbolic secant; sech
asinh(x)
1
√
−∞ < x < ∞
x = 21 ln( 11+xx ), 1 < x < 1 −
−1
−
Chen CL
16
Test Your Understanding T3.1-6 For several values of x in the range 0 sin(ix) = i sinh x.
≤ x ≤ 5,
confirm that
Chen CL
17
User-Defined Functions function [output variables] = function_name(input variables)
Function files are useful when one needs to repeat a set of commands several times
A function file should be stored as: function_name.m
All the variables in a function file are local (their values are available within the function)
function z = fun(x,y) u = 3*x; z = u + 6*y.^2;
v = fun(3,7) v = 303
Chen CL
18
User-Defined Functions function [output variables] = function_name(input variables)
Function files are useful when one needs to repeat a set of commands several times
A function file should be stored as: function_name.m
All the variables in a function file are local (their values are available within the function)
Function line
Filename
function
[area square]
=
square(side);
square.m
function function
area square [volume box]
= =
square(side); box(height,width,length);
square.m box.m
function function
[area circle,circumf] sqplot(side);
=
circle(radius);
circle.m sqplot.m
Chen CL
19
Example: Falling Object The following function, called drop, computes a falling object’s velocity and distance dropped. Input variables: acceleration g, initial velocity v0, elapsed time t. Output variables: v(t) = gt + v0; d(t) = 0.5gt 2 + v0t Save this function as drop.m function [dist, vel] = drop(g, vO, t); % computes the distance travelled and the % velocity of a dropped object, as functions % of g, the initial velocity vO, and the time t. % vel = g*t + vO; dist = 0.5*g*t.^2 + vO*t; %%%% end of function
Chen CL
20
a = 32.2; initial_speed = 10; time = 5; [feet_dropped1, speed] = drop(a, initial_speed, time); [feet_dropped2, speed] = drop(32.2, 10, 5); [feet_dropped, speed] = drop(32.2, 10, [0:0.2:5]); plot([0:0.2:5],feet_dropped,’o’, [0:0.2:5],feet_dropped,.. [0:0.2:5],speed, ’x’, [0:0.2:5],speed) 500
450
400
350
300
250
200
150
100
50
0 0
0.5
1
1.5
2
2.5
3
3.5
4
4.5
5
Chen CL
21
Example: Using Global Variables Engineers often need to estimate the pressures and volumes of a gas in a container. The ideal gas law provides one way of making the estimate. The law is P =
RT ˆ V
More accurate estimates can be made with the van der Waals equation: RT P = ˆ b V
− −
a ˆ2 V
where the term b is a correction for the volume of the molecules, and the term ˆ 2 is a correction for molecular attractions. The gas constant is R, the a/V ˆ . The value of R is the absolute temperature is T , and the gas specific volume is V same in both equations and for all gases; it is R = 0.08206 liter atmosphere/mole K. The values of a and b depend on the type of gas. For example, for chlorine (C2), a = 6.49 and b = 0.0562 in these units. Write two user-defined functions,
Chen CL
22
one to compute the pressure using the ideal gas law, and one using the van der Waals equation. Develop a solution without using global variables, and one using
global variables.
Solution:
We can write the following for the ideal gas law: function P = ideal_1(T,Vhat,R) P = R*T./Vhat; %% end of this function
Note: We should use array division because the user might call the function using Vhat as a vector
Avoid entering R when calling this function: function P = ideal_2(T,Vhat) % this requires liters, atmosphere, and mole units ! R = 0.08206; P = R*T./Vhat; %% end of this function
Chen CL
23
Declare R as a global variable function P = ideal_3(T,Vhat) global R P = R*T./Vhat; %% end of this function global R R = 0.08206; ideal_3([300,330],20)
ans = 1.2309
1.3540
In van der Waals equation, constants depend on particular gas function P = vdwaals_1(T,Vhat,R,a,b) P = R*T./(Vhat-b)-a./Vhat.^2 %% end of this function
A simpler function
Chen CL
function P = vdwaals_2(T,Vhat) % For chlorine only, and liter, atmosphere, and mole units! R = 0.08206; a = 6.49 ; b = 0.0562; P = R*T./(Vhat-b)-a./Vhat.^2 %% end of function
Use global variables function P = vdwaals_3(T,Vhat) % For chlorine only, and liter, atmosphere, and mole units! global R, a, b P = R*T./(Vhat-b)-a./Vhat.^2 %% end of function global R, a, b R = 0.08206; a = 6.49 ; b = 0.0562; P = vdwaals_3(300, 20)
P = 1.3416
24
Chen CL
25
Minimization and Root-finding Functions Function
Description
fminbnd(’function’,x1,x2)
Returns a value of x in the interval x1 x x2 that corresponds to a minimum of the singlevariable function described by the string ’function’ Uses the starting vector x0 to find a minimum of the multivariable function described by the string ’function’ Uses the starting value x0 to find a zero of the single-variable function described by the string ’function’
fminsearch(’function’,x0)
fzero(’function’,x0)
≤ ≤
Chen CL
26
Applications: Finding the Zero of A Function x
−
y = x + 2e
−3 function y = f144(x) y = x + 2*exp(-x) - 3; %% end of function, % save as f144.m
x = [-1:0.1:5]; y = x + 2*exp(-x) - 3; z = 0.*x; plot(x,y,x,z)
x = fzero(’f144’,-0.5); y = fzero(’f144’,3); x, y
2.5
2
1.5
x = -0.5831 y = 2.8887
1
0.5
0
−0.5
−1
−1.5 −1
0
1
2
3
4
5
Chen CL
27
Applications: Minimizing A Function of One Variable fminbnd(’cos’,0,4) ans = 3.1416
minimum of y = 1
function y = f144a(x) y = 1 - x.*exp(-x); %% end, saved in f144a.m z = fminbnd(’f144a’,0,5) z = 1.0000
x
−
− xe
,
0
≤x≤5
Chen CL
28
Applications: Minimizing A Function of One Variable Minimum of 0.025x5
4
3
− 0.0625x − 0.333x
+ x2,
x = [-1:0.1:4]; y = .025*x.^5-.0625*x.^4-.333*x.^3+x.^2; plot(x,y), xlabel(’x’), ylabel(’y’) 4.5
4
3.5
3
2.5 y
2
1.5
1
0.5
0
−1 ≤ x ≤ 4
Chen CL
29
Applications: Minimizing A Function of One Variable z1 = fminbnd(’.025*x.^5-.0625*x.^4-.333*x.^3+x.^2’,-1,4) z2 = fminbnd(’.025*x.^5-.0625*x.^4-.333*x.^3+x.^2’, 1,4) z1 = 2.0438e-006 z2 = 1
Chen CL
30
Applications: Minimizing A Function of Several Variables x2 −y2
−
minimum of f = xe
, near (0, 0)
function f = f146(x) f = x(1).*exp(-x(1).^2-x(2).^2); %% end, stored in f145.m fminsearch(’f146’,[0,0]) % [f, fval] = fminsearch(’f146’,[0,0]) ans = -0.7071
0.0000
Chen CL
31
Application: Optimization of An Irrigation Channel The following figure shows the cross section of an irrigation channel. A preliminary analysis has shown that the cross-sectional area of the channel should be 100 ft2 to carry the desired water-flow rate. To minimize the cost of concrete used to line the channel, we want to minimize the length of the channel’s perimeter. Find the values of d, b, and θ that minimize this length. sin θ = ad , a = sind θ 2d L = b + 2a = b + sin θ d tan θ = ad , a = tan θ
⇒
2
1 2
× ad ⇒ 100
= ad =
d2
tan θ
2
d = db + tan θ
b =
L =
1
d
100
d
100
−
− d
2
d
tan θ
2d + tan θ sin θ
Chen CL
32
Application: Optimization of An Irrigation Channel function L = channel(x) L = 100./x(1) - x(1)./tan(x(2)) + 2*x(1)./sin(x(2)); aprime = x(1)./tan(x(2)); x(3) = 100./x(1)-aprime; x(4) = x(3) + 2*aprime; x = fminsearch(’channel’,[10,1,15,20]) x = 7.5984
1.0472
16.7030
20.5622
Answer: d = 7.5984 ft, θ = 1.0472 rad (60o), b = 16.7030 ft, top wide = 20.5622 ft
Chen CL
33
Test Your Understanding T3.2-1 The equation e 0.2x sin(x + 2) = 0.1 has three solutions in the interval 0 < x < 10. Find these three solutions. −
T3.2-2 The function y = 1 + e 0.2x sin(x + 2) has two minimum points in the interval 0 < x < 10. Find the values of x and y at each minimum. −
T3.2-3 Find the depth d and angle θ to minimize the perimeter length of the channel shown in Figure 3.5-3 to provide an area of 200 ft2.