Upload
augusto-de-la-cruz-camayo
View
283
Download
1
Embed Size (px)
Citation preview
8/11/2019 6 Programming with MATLAB.pdf
1/66
Programming with
MATLAB
Cheng-Liang ChenPSELABORATORY
Department of Chemical EngineeringNational TAIWAN University
8/11/2019 6 Programming with MATLAB.pdf
2/66
Chen CL 1
Relational Operators
Six relational operators
Relational operator Meaning
< Less than.
Greater than.
>= Greater than or equal to.
== Equal to.
= Not equal to.
Note: single = is assignmentor replacement
8/11/2019 6 Programming with MATLAB.pdf
3/66
Chen CL 2
Result of comparison: (can be used as a variable)
1 if the comparison is true
0 if the comparison is false
x = 2 ;
y = 5 ;
z = x < y,...
w = x > y
z =
1
w =
0
Compare arrays
x = [ 6, 3, 9];
y = [14, 2, 9];
z = (x < y),...
p = (x ~= y),...
q = (x > 8)
z =
1 0 0p =
1 1 0
q =
0 0 1
z = x(x
8/11/2019 6 Programming with MATLAB.pdf
4/66
Chen CL 3
Logical Operators and Functions
Three logical operators
Operator Name Definition
NOT A returns an array the same dimension asA; the new array hasones whereA is zeroandzeros where A is nonzero.
& ANDA&B returns an array the same dimension asA and B; the new array has ones where bothA and B have nonzero elements and zeros
where either A orB is zero.| OR
A|B returns an array the same dimension as Aand B; the new array hasones where at leastone element in A or B is nonzero and zeros
where A andB are both zero.
8/11/2019 6 Programming with MATLAB.pdf
5/66
Chen CL 4
Element-by-element operations (exceptNOT)
x = [ 6, 3, 9];
y = [14, 2, 9];
z = ~x,...p = x > y
q = x y)
% = ( x < = y )
z =
0 0 0
p =
0 1 0
q =
1 0 1
r =
1 0 1z = 0&3
w = 2&3
z =0
w =
1
z = [5,-3,0,0]&[2,4,0,5]
z =
1 1 0 0
C C
8/11/2019 6 Programming with MATLAB.pdf
6/66
Chen CL 5
Order of Precedence for Operator Types
First Parentheses; evaluated starting with the innermost pair.
Second Arithmeticoperators and NOT(
); evaluated fromleft to right.
Third Relationaloperators; evaluated fromleft to right.Fourth Logical AND.
Fifth Logical OR.
z = 5 < 6 & 1 % ( 5 < 6 ) & 1
z =
1
x = [ 6, 3, 9];
y = [14, 2, 9];
a = [ 4, 3, 12];
z = x > y & a ,...
% = (x>y) & aw = x > y & x > a
% = (x>y) & (x>a)
z =
0 1 0
w =
0 0 0
~(4 > 5) is equivalent to 5 >= 4
5 < x < 10 is equivalent to (5
8/11/2019 6 Programming with MATLAB.pdf
7/66
Chen CL 6
z = ~3==7|4==6 %((~3)==7)|(4==6)
z =
0
x = xor([3,0,6],[5,0,0])
y = [3,0,6]&[5,0,0]z = [3,0,6]|[5,0,0]
x =
0 0 1
y =
1 0 0z =
1 0 1
x = [1, 1, 0, 0];
y = [1, 0, 1, 0];
Truth_table = [x, y, ~x, x|y, x&y, xor(x,y)]Truth_table =
1 1 0 1 1 0
1 0 0 1 0 1
0 1 1 1 0 1
0 0 1 0 0 0
x y x x|y x&y xor(x, y)true true false true true falsetrue false false true false true
false true true true false true
false false true false false false
Ch CL 7
8/11/2019 6 Programming with MATLAB.pdf
8/66
Chen CL 7
Logical Operators andfindFunction
Logical function Definition
any(X) Returns a scalar, which is 1 if any of the elements in thevectorx is nonzeroand0 otherwise.
any(A) Returns a row vector having the same number of column asA and containing ones and zeros, depending on whether or
not the corresponding column of the matrix Acontains anynonzero elements.
all(X) Returns a scalar, which is1 if all the elements in the vectorx are nonzeroand0 otherwise.
all(A) Returns a row vector having the same number of column
as the matrix A and containing ones and zeros, dependingon whether or not the corresponding column of A has allnonzero elements.
find(A) Computes an array containing the indices of the nonzeroelementsof the array A.
Ch CL 8
8/11/2019 6 Programming with MATLAB.pdf
9/66
Chen CL 8
Logical function Definition
[u,v,w] = find(A) Computes the arraysuandv containing the row and columnindices of the nonzero elements of the arrayAand computes
the array w containing the values of the nonzero elements.The array w may be omitted.
finite(A) Returns an array of the same dimension as A with oneswhere the elements ofA are finite and zeros elsewhere.
isnan(A) Returns an array of the same dimension as A with ones
where A has NaN and zeros elsewhere. (NaN stands forNota Number, which means an undefined result.)
isinf(A) Returns an array of the same dimension as A, with oneswhere A has inf and zeros elsewhere.
isempty(A) Returns a 1 ifA is an empty matrix and 0 otherwise.
isreal(A) Returns a 1 ifA has no elements with imaginary parts and0 otherwise.
xor(A,B) Returns an array the same dimension as A andB; the newarray has ones where either A or B is nonzero, but notboth, and zeros where A and B are either both nonzero orboth zero.
Ch CL 9
8/11/2019 6 Programming with MATLAB.pdf
10/66
Chen CL 9
Logical Operators andfindFunctionExample
x = [5,-3,0,0,8];y = [2, 4,0,5,7];
L_nonzero = find(x&y) ,...
values = y(x&y) ,...
how_many = length(values)
L_nonzero =1 2 5
values =
2 4 7
how_many =
3
Chen CL 10
8/11/2019 6 Programming with MATLAB.pdf
11/66
Chen CL 10
Test Your Understanding
T4.2-1Ifx= [5,3, 18, 4] and y = [9, 13, 7, 4], what will be the resultof the following operations ? UseMATLABto check your answer.
1. z= y > x2. z=x&y3. z=x|y4. z=xor(x, y)
Chen CL 11
8/11/2019 6 Programming with MATLAB.pdf
12/66
Chen CL 11
Example: Height and Speed of A Projectile
The height and speed of a projectile (such as a thrown ball) launched with a speed
ofv0 at an angle A to the horizontal are given by h(t) =v0tsinA 0.5gt2
,v(t) =
v20 2v0gtsinA+g2t2, where g is the acceleration due to gravity.
The projectile will strike the ground when h(t) = 0, which gives the time to hit,thit= 2(v0/g) sin(A). Suppose that A= 40
o, v0= 20 meters/second, andg= 9.81 meters/second2. Use the MATLAB relational and logical operators to
find the times when the height is no less than 6 meters and the speed issimultaneously no greater than 16 meters/second. In addition, discuss anotherapproach to obtaining a solution.
Solution:
The key to solving this problem with relational and logical operators is to use thefind command to determine the times at which the logical expression(h>=6)&(v
8/11/2019 6 Programming with MATLAB.pdf
13/66
Chen CL 12
Example: Height and Speed of A Projectile
% Set the values for initial speed, gravity, and angle.
v0 = 20; g = 9.81; A=40*pi/180;% Compute the time to hit.
t_hit = 2*v0*sin(A)/g;
% Comput the arrays containing time, height, and speed.
t = [0 : t_hit/100 : t_hit];
h = v0*t*sin(A) - 0.5*g*t.^2;
v = sqrt(v0^2 - 2*v0*g*sin(A)*t + g^2*t.^2);
h6=6*t.^0; v16=16*t.^0;
subplot(3,1,1)
plot(t,h,t,h6,Linewidth,2)
set(gca,LineWidth,2,FontSize,12)
xlabel(\bf Time,FontSize,12)ylabel(\bf Height,FontSize,12)
subplot(3,1,2)
plot(t,v,t,v16,Linewidth,2)
set(gca,LineWidth,2,FontSize,12)
xlabel(\bf Time,FontSize,12)
ylabel(\bf Velocity,FontSize,12)
Chen CL 13
8/11/2019 6 Programming with MATLAB.pdf
14/66
Chen CL 13
Example: Height and Speed of A Projectile
% Determine when the height is no less than 6,
% and the speed is no greater than 16.
y = h>=6 & v=6 & v
8/11/2019 6 Programming with MATLAB.pdf
15/66
Chen CL 14
Example: Height and Speed of A Projectile
t_1 =
0.8649
t_2 =
1.7560
Chen CL 15
8/11/2019 6 Programming with MATLAB.pdf
16/66
Chen CL 15
Test Your Understanding
T4.2-2Consider the problem given in the previous Example. Use relationaland logical operators to find the times for which either theprojectiles height is less than 4 meters or the speed is greater than17 meters per second. Plot h(t) and v(t) to confirm your answer.
Chen CL 16
8/11/2019 6 Programming with MATLAB.pdf
17/66
Chen CL 16
Conditional Statements
% Decision making (I)
If I get a raise,
I will buy a new car
. (period)
% Decision making (II)
If I get at least a $100 per week raise,I will buy a new car;
else,
I will put the raise into savings
. (period)
% Decision making (III)If I get at least a $100 per week raise,
I will buy a new car;
else, if the raise is greater than $50,
I will buy a new stereo;
otherwise,
I will put the raise into savings
. (period)
Chen CL 17
8/11/2019 6 Programming with MATLAB.pdf
18/66
Chen CL 17
TheifStatement
if logical expression
statements
end
i f x > = 0y = sqrt(x)
end
if x >= 0, y = sqrt(x), end
Chen CL 18
8/11/2019 6 Programming with MATLAB.pdf
19/66
Chen CL 18
NestedifStatements
if logical expression 1
if logical expression 2
statementsend
end
if (logical expression 1) & (logical expression 2)
statements
end
Chen CL 19
8/11/2019 6 Programming with MATLAB.pdf
20/66
Chen CL 19
z =
x+
y
w = log x 3log yz = 0 ; w = 0 ;
if (x >= 0)
if (y >= 0)
z = sqrt(x) + sqrt(y)
w = log(x) - 3*log(y)
end
end
z = 0 ; w = 0 ;
if (x >= 0)&(y >= 0)z = sqrt(x) + sqrt(y)
w = log(x) - 3*log(y)
end
%%% Nested if statements
if logical expression 1
statement group 1
if logical expression 2
statement group 2
end
end
Chen CL 20
8/11/2019 6 Programming with MATLAB.pdf
21/66
Chen CL 20
TheelseStatement
if logical expression
statement group 1
else
statement group 2end
y=
x for x 0
ex 1 for x = 0y = sqrt(x)
else
y = exp(x) - 1
end
Chen CL 21
8/11/2019 6 Programming with MATLAB.pdf
22/66
Note: For logical expression of an array, the test returns a value of
trueonly ifALL the elements of the logical expression are nonzero !
x = [4, -9, 25];i f x < 0
disp(All elements of)
disp(x are negative.)
else
y = sqrt(x)
end
y =
2 0+3.000i 5
x = [4, -9, 25];i f x > = 0
y = sqrt(x)
else
disp(Some of the elements)
disp( of x are negative.)
end
Some of the elements
of x are negative.
Chen CL 22
8/11/2019 6 Programming with MATLAB.pdf
23/66
TheelseifStatement
if logical expression 1
statement group 1
elseif logical expression 2
statement group 2
elsestatement group 3
end
Chen CL 23
8/11/2019 6 Programming with MATLAB.pdf
24/66
y=
ln x if x 5x if 0 x = 5
y = log(x)
else
i f x > = 0y = sqrt(x)
end
end
% Note: no action for x=-2 ?
i f x > = 5
y = log(x)
elseif x >= 0y = sqrt(x)
end
y=
ln x if x >10
x if 0 x 10ex 1 if x 1 0
y = log(x)
elseif x >= 0
y = sqrt(x)
else
y = exp(x) - 1
end
Chen CL 24
8/11/2019 6 Programming with MATLAB.pdf
25/66
i f x > 1 0
y = log(x)
i f y > = 3
z = 4*yelseif y >= 2.5
z = 2*y
else
z = 0
end
else
y = 5*x
z = 7*x
end
Chen CL 25
8/11/2019 6 Programming with MATLAB.pdf
26/66
Test Your Understanding
T4.3-1Enter the script file shown above, whose flowchart is show in Figure
4.3-6. Run the file for the following values ofx. Check the program
results by hand: x= 11, 25, 2, 13.
T4.3-2
Given a number x and the quadrant q(q = 1, 2, 3, 4), write a
program to compute sin1(x) in degrees, taking into account the
quadrant. The program should display an error message if
|x
|>1.
Chen CL 26
8/11/2019 6 Programming with MATLAB.pdf
27/66
Strings and Conditional Statements
name = Leslie Student
name =
Leslie Student
number = 123
number =123
size(name)
ans =
1 14
name(8)
ans =
S
first_name = name(1:6)
first_name =Leslie
full_name = [name(1:6), C. ,name(7:14)]
full_name =
Leslie C. Studentfull_name(8) = F
full_name =
Leslie F. Student
findstr(full_name,e)
ans =
2 6 15
% letter e occurs in 2nd,
% 6th, and 15th columns
Chen CL 27
8/11/2019 6 Programming with MATLAB.pdf
28/66
Input Prompts and Output Messages
One of the most important applications for stringsis to create
Input PromptsandOutput Messages
x = input(prompt,string)
response = input(Do you want to continue? Y/N [Y]: ,s);
if ( isempty(response) | (response == Y) | (response == y) )response = Y
else
response = N
end
Chen CL 28
8/11/2019 6 Programming with MATLAB.pdf
29/66
forLoops
for loop variable = m:s:n
statements
end
for k = 5:10:35x = k^2
end
for x = 0:2:10, y = sqrt(x), end
Chen CL 29
8/11/2019 6 Programming with MATLAB.pdf
30/66
Nested Loops
function A = specmat(n)A = ones(n);
for r = 1:n
for c = 1:n
if (r>1)&(c>1)
s = A(r-1,c) + A(r,c-1);
if s
8/11/2019 6 Programming with MATLAB.pdf
31/66
Test Your Understanding
T4.4-1
Write a program to produce the following matrix:
A=
4 8 12
10 14 18
16 20 24
22 26 30
Chen CL 31
8/11/2019 6 Programming with MATLAB.pdf
32/66
Rules for UsingforLoops m:s:n
The step value smay be negative.For example, k= 10 : 2 : 4 produces k= 10, 8, 6, 4.
Ifs is omitted, the step value defaults to one.
Ifs is positive, the loop will not be executed ifm > n.
Ifs is negative, the loop will not be executed ifm is less than n.
Ifm equals n, the loop will be executed only once.
If the step value s is not an integer, round-off errors can cause the
loop to execute a different number of passes than intended.
Chen CL 32
8/11/2019 6 Programming with MATLAB.pdf
33/66
breakandcontinueCommands
for k = 1:10
x = 50 - k^2;i f x < 0
break
end
y = sqrt(x)end
% The program execution
% jumps to
% ------HERE------
% if the break command
% is executed
x = [10,1000,-10,100];
y = NaN*x;
for k = 1:length(x)
if x(k) < 0
continue
end
y(k) = log10(x(k));
end
y
y =1 3 NaN 2
Chen CL 33
8/11/2019 6 Programming with MATLAB.pdf
34/66
Vector as Loop Variables
A = [1,2,3,4,5,6];
f o r v = Adisp(v)
end
12
3
4
5
6
A = [1,2,3,4,5,6];
n = 3 ;for k = 1:n
v = A(:,k)
end
v =1
v =
2
v =
3
Chen CL 34
8/11/2019 6 Programming with MATLAB.pdf
35/66
Implied Loops
x = [0:5:100];
y = cos(x);
for k = 1:21
x = (k-1)*5;
y(k) = cos(x);end
y = find(x>0)
j=0;
for i=1:length(x)
if x(i)>0j = j + 1 ;
y(j)=i;
end
end
Chen CL 35
8/11/2019 6 Programming with MATLAB.pdf
36/66
Test Your Understanding
T4.4-1
Write a for loop that is equivalent to the command sum(A), where
A is a matrix.
Chen CL 36
8/11/2019 6 Programming with MATLAB.pdf
37/66
Example: Data Sorting
A vector x has been obtained from measurements. Suppose we want to consider
any data value in the range0.1< x
8/11/2019 6 Programming with MATLAB.pdf
38/66
%%%%% Method 1: use a for loop %%%%%
x = [1.92,0.05,-2.43,-0.02,0.09,0.85,-0.06];
y = [];z = [];
for k = 1:length(x)if abs(x(k)) >= 0.1
y = [y,x(k)];
else
z = [z,x(k)];
end
end
xnew = [y, zeros(size(z))]
xnew =
1.9200 -2.4300 0.8500 0 0 0 0
%%%%% Method 2: use find function %%%%%
x = [1.92,0.05,-2.43,-0.02,0.09,0.85,-0.06];
y = x(find(abs(x) >= 0.1));
z = zeros(size(find(abs(x)
8/11/2019 6 Programming with MATLAB.pdf
39/66
EX: Flight of An Instrumented Rocket
All rockets lose weight as burn fuel; thus the mass of the system is variable. Thefollowing equations describe the speed v and height h of a rocket launched
vertically, neglecting air resistance. They can be derived from Newtons law [Beerand Johnston 1997].
v(t) = u ln
m0m0qt
gt
h(t) = u
q
(m0
qt) l n (m0
qt)
+u ln (m0+ 1) t gt2
2 m0u
q ln(m0)
where m0 is the rockets initialmass, qis the rate as which the rocket burns fuelmass (assumed constant), u is the exhaust velocity of the burned fuel relative to
the rocket (also assumed constant), and g is the acceleration due to gravity. Let bbe the burn time, after which all the fuel is consumed. Thus the rockets masswithoutfuel is me= m0 qb. At the burn time, the rocket height is
h(b) = u
q(me) l n (me) +u ln (m0+ 1) b
gb2
2 m0u
q ln(m0)
Chen CL 39
F b h k i l d h d h d d h i h
8/11/2019 6 Programming with MATLAB.pdf
40/66
For t > b the rocket engine no longer produces thrust, and the speed and heightare given by
v(t) = v(b) g(t b) (fort > b)h(t) = h(b) +v(b)(t b) g(t b)
2
2 ()
The time tp to reach the peak height is found by setting v(t) = 0. The result is
tp= b+v(b)/g. Substituting this expression into the expression (*) for h(t) gives
the following expression for the peak height: hp=h(b) +v2
(b)/(2g). The time atwhich the rocket hits the ground is thit= tp+
2hp/g.
Suppose the rocket is carrying instruments to study the upper atmosphere, and we
need to determine the amount of time spent above 50, 000 feet as a function of
the burn time b (and thus as a function of the fuel mass qb). Assume that we are
given the following values: me= 100 slugs, q= 1 slug per second, u= 8000 feet
per second, and g= 32.2 feet per second2. If the rockets maximum fuel load is
100 slugs, the maximum value ofb is 100/q= 100 seconds.
Write a MATLAB program to solve this problem.
Chen CL 40
S l i
8/11/2019 6 Programming with MATLAB.pdf
41/66
Solution
Pseudocode for developing the program appears in the following. A for loop is alogical choice to solve this problem because we know the burn timebandthit, thetime it takes to hit the ground. A MATLAB program to solve this problemappears in the following. It has two nested for loops. The inner loop is over timeand evaluates the equations of motion at times spaced1/10 of a second apart.This loop calculates the duration above 50, 000 feet for a specific value of theburn timeb. We can obtain more accuracy by using a smaller value of the timeincrement dt. The outer loop varies the burn time in integer values from b= 1 to
b= 100. The final result is the vector of durations for the various burn time. Thfollowing Figure gives the resulting plot.
Chen CL 41
8/11/2019 6 Programming with MATLAB.pdf
42/66
Enter data.
Increment burn time from 0 to 100. For each burn-time value:
Computem0, vb, hb, hp.
Ifhp hdesired,Computetp, thit.
Increment time from 0 to thit.
Compute height as a function of time, using
the appropriate equation, depending on whether
burnout has occurred.
Compute the duration above desired height.
End of the time loop.
Ifhp< hdesired, set duration equal to zero.
End of the burn-time loop.Plot the result.
Chen CL 42% Script file rocket1.m:% Computes flight duration as a function of burn time
8/11/2019 6 Programming with MATLAB.pdf
43/66
% Computes flight duration as a function of burn time.
% Basic data values.
m_e = 100; q = 1; u = 8000; g = 32.2;
dt = 0.1; h_desired = 50000;
for b = 1:100 % Loop over burn time.
burn_time(b) = b;
% % Following lines implement the formulas in text.m_0 = m_e + q*b;
v_b = u*log(m_0/m_e) - g*b;
% h_b = ((u*m_e)/q)*log(m_e/(m_e+q*b))+u*b-0.5*g*b^2;
h_b = ((u*m_e)/q)*log(m_e) + u*(log(m_0)+1)*b ...
- 0.5*g*b^2 - ((u*m_0)/q)*log(m_0);
h_p = h_b + v_b^2/(2*g);
if h_p >= h_desired;
% % Calculate only if peak height > desire height.t_p = b + v_b/g; %Compute peak time.
t_hit = t_p + sqrt(2*h_p/g); %Compute time to hit.
% for p = 0:t_hit/dt:t_hit
for p = 0:t_hit/dt
% % Use a loop to compute the height vector.
k = p+1; t = p*dt; time(k) = t;
% k = p + 1; t = p*dt; time(k) = t;
i f t < = b% % Burnout has not yet occurred.
h(k) = (u/q)*(m_0 - q*t)*log(m_0 - q*t) ...
+ u*(log(m_0) + 1)*t - 0.5*g*t^2 ...
- (m_0*u/q)*log(m_0);
else
% % Burnout has occurred.
h(k) = h_b + v_b*(t - b) - 0.5*g*(t - b)^2;
end
end
% % Compute the duration.
duration(b) = ...
length(find(h>=h_desired))*dt;else
% % Rocket did not reach desired heig
duration(b) = 0;
end
end % Plot the results.
plot(burn_time,duration) ,...
xlabel(Burn Time (sec)),...
ylabel( Duration (sec)),...title(Duration Above 50,000 Feet)
0 10 20 30 40 50 60 70 80 90 1000
20
40
60
80
100
120
140
160
180
Burn Time (sec)
Duration(sec)
Duration Above 50,000 Feet
Chen CL 43
hil L
8/11/2019 6 Programming with MATLAB.pdf
44/66
whileLoops
The while loop is used when
the looping process terminates
because a specified condition
is satisfied, and the number of
passes in not known in advance.
while logical expression
statements
end
A practical application ofwhileloop is when we want the loop to
continue as long as a certain statement in true
Chen CL 44
x = 5 ; x=1;
8/11/2019 6 Programming with MATLAB.pdf
45/66
x = 5 ;
while x < 25
disp(x)
x = 2*x-1;
end
5
9
17
x=1;
while x ~= 5
disp(x)
x = x+1;
end
1
2
3
4
Chen CL 45
E l Ti t R h S ifi d H i ht
8/11/2019 6 Programming with MATLAB.pdf
46/66
Example: Time to Reach a Specified Height
Consider the variable-mass rocket treated in previous Example.Write a MATLAB program to determinehow long it takes for the
rocket to reach 40, 000feet if the burn time is 50seconds.
Solution: The pseudocode appears in the following Table. Because we do not
know the time required, a while loop is convenient to use. The program performs
the task and is a modification of the previous program. Note that the new
program allows for the possibility that the rocket might not reach 40, 000 feet. It
is important to write your program to handle all such foreseeable circumstances.
The answer given by the program is 53 seconds.
Chen CL 46
8/11/2019 6 Programming with MATLAB.pdf
47/66
Enter data.
Computem0, vb, hb, hp.
Ifhp hdesired,Use a while loop to increment time and compute height until desired heightis reached.
Compute height as a function of time, using the appropriate equation,
depending on whether burnout has occurred.
End of the results.
Display the results.
Ifhp< hdesired, rocket cannot reach desired height.
Chen CL 47
% Script file rocket2 m % Compute time to reach desired height
8/11/2019 6 Programming with MATLAB.pdf
48/66
% Script file rocket2.m % Compute time to reach desired height.
% Set the data values.
h_desired = 40000; m_e = 100; q = 1;
u = 8000; g = 32.2; dt = 0.1; b = 50;
% Compute values at burnout, peak time, and height.
m_0 = m_e + q*b; v_b = u*log(m_0/m_e) - g*b;
h_b = ((u*m_e)/q)*log(m_e/(m_e+q*b))+u*b- .5*g*b^2;t_p = b + v_b/g; h_p = h_b + v_b^2/(2*g);
% If h_p > h_desired, compute time to reached h_desired.
if h_p > h_desired
h = 0 ; k = 0 ;
while h < h_desired % Compute h until h = h_desired.
t = k*dt; k = k + 1;
i f t < = b
h = (u/q)*(m_0 - q*t)*log(m_0 - q*t) ... % Burnout has not yet occurred.+ u*(log(m_0) + 1)*t - 0.5*g*t^2 ...
- (m_0*u/q)*log(m_0);
else
h = h_b - 0.5*g*(t - b)^2 + v_b*(t - b); % Burnout has occurred.
end
end
% Display the results.
disp(The time to reach the desired height is:)
disp(t)
else
disp(Rocket cannot achieve the desired height.)
end
The time to reach the desired height is:
53
Chen CL 48
Test Yo U de sta di
8/11/2019 6 Programming with MATLAB.pdf
49/66
Test Your Understanding
T4.4-3
Rewrite the following code using a whileloop to avoid using thebreakcommand.
for k = 1:10
x = 50 - k^2;
i f x < 0
break
end
y = sqrt(x)
end
T4.4-4
Find to two decimal places the largest value ofx before the error in
the series approximation ex
1 +x+x2/2 +x3/6 exceeds 1
percent. (answer: x= 0.83)
Chen CL 49
The switch Structure
8/11/2019 6 Programming with MATLAB.pdf
50/66
TheswitchStructureTheswitchstructure provides an alternative to using theif,elseif,
andelsecommands.
Anything programmed usingswitchcan also be programmed usingifstructures. However, theswitchcan provide more readable codes.
switch input expression
(scalar or string)
case value1statement group 1
case value2
statement group 2
...
...
otherwise
statement group n
end
switch angle
case 45
disp(Northeast)
case 135
disp(Southeast)
case 225
disp(Southwest)
case 315disp(Northwest)
otherwise
disp(Direction Unknow
end
Chen CL 50
8/11/2019 6 Programming with MATLAB.pdf
51/66
Use a string variable for inputexpression to result in veryreadable programs
t = [0:100]; x = exp(-t).*sin(t);
response = ...
input(Type min, max, or sum.,s)
response = lower(response);switch response
case min
minimum = min(x)
case max
maximum = max(x)
case sumtotal = sum(x)
otherwise
disp(You have not entered a proper choice.)
end
Theswitchstatement can handlemultiple conditions in a singlecase statement by enclosing thecasevalue in a cell array
switch angle
case {0,360}
disp(North)
case {-180,180}disp(South)
case {-270,90}
disp(East)
case {-90,270}
disp(West)
otherwisedisp(Direction Unknown)
end
Chen CL 51
Test Your Understanding
8/11/2019 6 Programming with MATLAB.pdf
52/66
Test Your Understanding
T4.5-1
Write a program using the switch structure to input one angle,whose value may be 45,45, 135degrees, and display the quadrant(1, 2, 3, or4) containing the angle.
Chen CL 52
Debugging MATLAB Programs
8/11/2019 6 Programming with MATLAB.pdf
53/66
DebuggingMATLABPrograms
function y = fun1(x)
avg = sum(x)/length(x);
y = fun2(avg,x);
function above = fun2(x,avg)
above = length(find(x>avg));
above = fun1([1,2,3,4,10])
above =
3
Chen CL 53
Debugging A Loop
8/11/2019 6 Programming with MATLAB.pdf
54/66
Debugging A Loop
function z = invest(x,r)
z = 0 ;
y = 1+0.01*r;
for k = 1:length(y)
z = z*y+x(k);
end
>>total = invest([1000,1500,2000],10)
total =
1000
Chen CL 54
Example: A College Enrollment Model (I)
8/11/2019 6 Programming with MATLAB.pdf
55/66
Example: A College Enrollment Model (I)
As a example of how simulation can be used for operations research, consider thefollowing college enrollment model. A certain college wants to analyze the effect
of admissions and freshman retention rate on the colleges enrollment so that it
can predict the future need for instructors and other resources. Assume that the
college has estimates of the percentages of students repeating a grade or leaving
school before graduating. Develop a matrix equation on which base a simulation
model that can help in this analysis.
Solution:Suppose that the current freshman enrollment is 500 students and the collegedecides to admit 1000 freshman per year from now on. The college estimates that10 percent of the freshman class will repeat the year. The number of freshman inthe following year will be 0.1(500) + 1000 = 1050, then it will be0.1(1050) + 1000 = 1105, and so on. Let x1(k) be the number of freshman in
year k, where k= 1, 2, 3, 4, 5, 6, . . .. Then in year k+ 1, the number of freshman
Chen CL 55
is given by
8/11/2019 6 Programming with MATLAB.pdf
56/66
is given by
x1(k+ 1) = 10 percent of previous freshman class repeating freshman year +1000new freshman
= 0.1x1(k) + 1000
Because we know the number of freshman in the first year of our analysis (whichis 500), we can solve this equation step to predict the number of freshman in thefuture.Let x2(k) be the number of sophomores in year k. Suppose that 15 percent of the
freshman do not return and that 10 percent repeat freshman year. Thus 75percent of the freshman class returns as sophomore. Suppose also 5 percent of thesophomores repeat the sophomore year and that200 sophomores each year transferfrom other schools. Then in year k+ 1, the number of sophomores is given by
x2(k+ 1) = 0.75x1(k) + 0.05x2(k) + 200
To solve this equation we need to solve the freshman equation at the sametime, which is easy to do with MATLAB. Before we solve these equations, let usdevelop the rest of the model.Let x3(k) andx4(k) be the number of juniors and seniors in year k. Suppose that5 percent of the sophomores and junior leave school and that 5 percent of the
sophomores, juniors, and seniors repeat the grade. Thus 90 percent of the
Chen CL 56
sophomores and juniors return and advance in grade. The models for juniors and
8/11/2019 6 Programming with MATLAB.pdf
57/66
sophomores and juniors return and advance in grade. The models for juniors andseniors are
x3(k+ 1) = 0.9x2(k) + 0.05x3(k)
x4(k+ 1) = 0.9x3(k) + 0.05x4(k)
These four equations can be written in the following matrix form:
x1(k+ 1)
x2(k+ 1)
x3(k+ 1)
x4(k+ 1)
=
0.1 0 0 0
0.75 0.05 0 0
0 0.9 0.05 0
0 0 0.9 0.05
x1(k)
x2(k)
x3(k)
x4(k)
+
1000
200
0
0
In the following example, we will see how to use MATLAB to solve such
equations.
Chen CL 57
Test Your Understanding
8/11/2019 6 Programming with MATLAB.pdf
58/66
Test Your Understanding
T4.7-1
Suppose that 70 percent of the freshman, instead of75 percent,return for the sophomore year. How does the previous equation
change ?
Chen CL 58
Example: A College Enrollment Model (II)
8/11/2019 6 Programming with MATLAB.pdf
59/66
Example: A College Enrollment Model (II)
To study the effects of admissions and transfer policies, generalize the enrollmentmodel in previous example to allow for varying admissions and transfers.Solution: Let a(k) be the number of new freshman admitted in the spring ofyeark for the following year k+ 1and let d(k) be the number of transfers into thefollowing years sophomore class. Then the model becomes
x1(k+ 1) = c11x1(k) +a(k)
x2(k+ 1) = c21x1(k) +c22x2(k) +d(k)
x3(k+ 1) = c32x2(k) +c33x3(k)
x4(k+ 1) = c43x3(k) +c44x4(k)
where we have written the coefficients c21, c22, and so on in symbolic, rather thannumerical, form so that we can change their values if desired.This model can be represented graphically by a state transition diagram, like the
one shown in the following Figure.
Chen CL 59
8/11/2019 6 Programming with MATLAB.pdf
60/66
Such diagrams are widely used to represent time-dependent and probabilisticprocesses. The arrows indicate how the models calculations are updated for eachvalues ofx1(k), x2(k), x3(k), andx4(k); that is, by the vector x(k), which is
called the state vector. The elements of the state vector are the state variablesdepend on both the previous values and the input a(k) andd(k).The four equations can be written in the following matrix form:
x1(k+ 1)
x2(k+ 1)x3(k+ 1)
x4(k+ 1)
=
c11 0 0 0
c21 c22 0 00 c32 c33 0
0 0 c43 c44
x1(k)
x2(k)x3(k)
x4(k)
+
a(k)
d(k)0
0
or more compactly as
x(k+ 1) =Cx(k) +b(k)
Chen CL 60
where
8/11/2019 6 Programming with MATLAB.pdf
61/66
x(k) =
x1(k+ 1)
x2(k+ 1)
x3(k+ 1)
x4(k+ 1)
b(k) =
a(k)
d(k)
0
0
and
C=
c11 0 0 0
c21 c22 0 0
0 c32 c33 0
0 0 c43 c44
Suppose that the initial total enrollment of1480 consists of500 freshman, 400sophomores,300 juniors, and 280 seniors. The college wants to study, over a10-year period, the effects of increasing admissions by 100 each year and transfersby50 each year until the total enrollment reaches 4000; then admissions and
transfers will be held constant. Thus the admissions and transfers for the next 10years are given by
a(k) = 900 + 100k
d(k) = 150 + 50k
fork= 1, 2, 3, . . . until the colleges total enrollment reaches 4000; then
admissions and transfers are held constant at the previous years levels. We cannot
Chen CL 61
determine when this event will occur without doing a simulation. The following
8/11/2019 6 Programming with MATLAB.pdf
62/66
g gTable gives the pseudocode for solving this problem.
Enter the coefficient matrix C and the initial enrollment vector x.
Enter the initial admissions and transfers, a(1) andd(1).
Set the first column of the enrollment matrix E equal tox.
Loop over years 2 to10.
If the total enrollment is 4000, increase admissions by 100 and transfersby50 each year.If the total enrollment is >4000, hold admissions and transfers constant.
Update the vector x, usingx = Cx + b.
Update the enrollment matrix E by adding another column composed ofx.
End of the loop over years 2 to10.
Plot the results.
Because we know the length of the study (10 years), a for loop is a natural choice.
We use an if statement to determine when to switch from the increasing
admissions and transfer schedule to the constant schedule. A MATLAB script file
Chen CL 62
to predict the enrollment for the next 10 years appears in the following. The
8/11/2019 6 Programming with MATLAB.pdf
63/66
Figure shows the resulting plot. Note that after year 4 there are more sophomores
than freshmen. The reason is that increasing transfer rate eventually overcomes
the effect of the increasing admission rate.
% Script file enroll1.m Computes college enrollment.
% Models coefficients.
C = [.1, 0, 0, 0; .75, .05, 0, 0; 0, .9, .05, 0; 0, 0, .9, .05];
% Initial enrollment vector.
x = [500; 400; 300; 280];
% Initial admissions and transfers.
a(1) = 1000; d(1) = 200;
% E is the 4 x 10 enrollment matrix.
E(:,1) = x;
% Loop over years 2 to 10.
for k = 2:10
% The following describes the admissions
% and transfer policies
if sum(x)
8/11/2019 6 Programming with MATLAB.pdf
64/66
x = C*x+b;
E(:,k) = x;
end
% Plot the results. (Demo in the class)
plot(E), hold,...
plot(E(1,:),o), plot(E(2,:),+), ...
plot(E(3,:),*), plot(E(4,:),x), ...
xlabel(Year), ylabel(Number of Students),...
gtext(Frosh),gtext(Soph),gtext(Jr),gtext(Sr),...
title(Enrollments as a Function of Time)
In actual practice this program would be run many times to analyze the effects of
different admissions and transfer policies and to examine what happens if different
values are used for the coefficients in the matrix C (indicating different dropout
and repeat rates).
Chen CL 64
Test Your Understanding
8/11/2019 6 Programming with MATLAB.pdf
65/66
Test Your Understanding
T4.7-1
In the previous program, line 16 and 17 compute the values ofa(k)and d(k). These lines are repeated here:
a(k) = 900 + 100 kd(k) = 150 + 50 k;
Why does the program contain the line a(1) = 1000; d(1) = 200 ?
Chen CL 65
8/11/2019 6 Programming with MATLAB.pdf
66/66
Thank You for Your AttentionQuestions Are Welcome