Part (1)Programming 2
Part (1)Programming 2
ﺍﻟﻤﺮﺣﻠﺔ ﺍﻟﺜﺎﻧﻴﺔ
ﺑﺮﻣﺠﺔ ﺍﻟﺤﺎﺳﺒﺎﺕ2
ﻡ.ﺩ.ﺳﻌﺪ ﺭﺣﻴﻢ
MATLAB For
Chemical Engineer
Introduction to MATLAB
MATLAB widely used in the engineering. It has many features and it could take
years to learn all of its capabilities. However, it’s basic functionality is quite easy to learn
and in the course of the next few weeks we will be learning how to manipulate and graph
data in MATLAB as well as writing simple programs to manipulate data. It offers a
powerful programming language, excellent graphics, and a wide range of expert
knowledge.
1
1. Getting Started
Start Matlab by double clicking the icon on the desktop, or from the start menu. To
use Matlab you can simply enter commands after the prompt (the >> is the Matlab
prompt).
Figure 1 below shows the default frame with the three standard Matlab windows.
2
1.1 Alternate windows:
The smaller of the two windows is alternate windows that can be accessed by
clicking on the tabs. Figure 2 shows the alternate windows and describes their functions.
The command window is the active window immediately appears after launching
Matlab. One enters Matlab commands after the ">>" prompt and presses enter to execute
the command. To recall the last commands entered, simply press the up or down arrows;
one can edit the commands before executing them. Multiple commands may be entered on
one line separated by commas. Separating commands by a semi-colon suppresses output to
the command window.
3
Note that the results of these computations are saved in variables whose names are
chosen by the user. If you need to obtain their values again, type their names and pressing
Enter key. If you type again:
>> s
s=
3
Only for short computations it is useful to execute Matlab straightaway from the
command line. The Editor Window is a word processor specifically designed for
MATLAB commands. Files that written in this window are called the m-files. Another
way to do calculations in MATLAB is to create an m-file with a series of commands and
then to run some or all of the commands in that file. To create an m-file, click file, new
and then m-files. The same statements that are entered in the command window can also
be used in an m file. You can also copy a command you try out in the command window
into an m file by using the copy and paste functions on the computer. Save the file under a
name that ends in .m by clicking file and using “save as” icon. (See Figure 3).
4
2. Numbers, Arithmetic Operations and Special Characters
There are three kinds of numbers used in MATLAB:
• integers
• real numbers
• complex numbers
In addition to these, MATLAB has three variables representing non-numbers:
(-Inf , Inf , NaN )
The –Inf and Inf are the negative and positive infinity respectively. Infinity is
generated by overflow or by the operation of dividing by zero. The NaN stands for Not-A-
Number and it is obtained as a result of the mathematically undefined operations such as
0.0/0.0.
The list of basic arithmetic operations in MATLAB includes six operations:
+ : addition
- : substraction
* : multiplication
/ : right division
\ : left division
^ : power
One can use Matlab like a calculator without specifying variables. Matlab has all the
standard mathematical operations. Try type:
>> 2+3
Matlab returns the answer:
ans=
5
>> 5^3
ans=
125
>>3.89*4.1
ans =
15.9490
>> 3*(23+14.7-4/6)/3.5
ans=
31.7429
5
The result of these operations is assigned to a default variable called ans and
displayed. Adding a semicolon to the end of the operation suppresses the output; try it out!
>>25*3;
Also type:
>> 1/0
Warning: Divide by zero.
ans =
Inf
>> Inf/Inf
ans =
NaN
3. Relational operations
Relational operators perform element-by-element comparisons between two numbers
as following meaning;
A < B Less than
A > B Greater than
A <= B Less than or equal
A >= B Greater than or equal
A == B Equal
A ~= B Not equal
Further, there is a menu of special characters that have specific uses.
Logical AND &
Logical OR |
Logical NOT ~
Colon :
Subscripting ( )
Brackets [ ]
Decimal point .
Continuation ...
Separator ,
Semicolon ; (suppresses the output of a calculation)
Assignment =
Quote ' statement '
Transpose '
Comment %
Note: anything after % is a comment and will be ignored by Matlab.
6
4. Variables
Variable names may be up to 19 characters long. Names must begin with a letter but
may be followed by any combination of letters, digits or underscores. Variables are
storage locations in the computer that are associated with an alphanumeric name. To
assign a value to a variable in MATLAB simply type the name of the variable, followed
by the assignment operator, =, followed by the value.
As an example, this is one way to compute 2+2:
>> a = 2
a=
2
>> b = 2
b=
2
>> c = a + b
c=
4
It is often annoying to have Matlab always print out the value of each variable. To
avoid this, put a semicolon after the commands:
>> a = 2;
>> b = 2;
>> c = a + b;
>> c
c=
4
Only the final line produces output. Semicolons can also be used to string together
more than one command on the same line:
>> a = 2; b = 2; c = a + b; c
c=
4
Of course Matlab will also allow more complicated operations:
>> a = 2;
>> b = -12;
>> c = 16;
>> qu1 = (-b + sqrt(b^2 - 4*a*c)) / (2*a)
qu1 =
4
7
Understand that 'matlab' is "case sensitive", that is, it treats the name 'C' and 'c' as two
different variables. Similarly, 'MID' and 'Mid' are treated as two different variables. Assign
two different values to the variables and print them out by entering their names separated
by a comma.
>>var=1.2
var =
1.2000
>>Var=-5.1
Var =
-5.1000
>>var, Var
var =
1.2000
Var =
-5.1000
8
5. Reporting format
By default MATLAB returns numerical expressions as decimals with 4 digits. The
format function is used to change the format of the output. Type format rat to have
MATLAB return rational expressions.
>> format rat
>> 5.1-3.3
ans =
9/5
To eliminate the extra spacing type format compact.
>> format compact
>> 5*7
ans =
35
Now type
>> format long
>> 3*(23+14.7-4/6)/3.5
ans=
31.74285714285715
>> format short e
>> 3*(23+14.7-4/6)/3.5
ans=
3.1743e+01
Note that the answer is accurate to four decimal places. Now type
>> format long e
ans=
3.174285714285715e+01
>> format short
ans=
31.7429
Note: format short will return the numerical expression to default. Also, the format
of reporting does not change the accuracy of the calculations only the appearance of the
answer on screen.
6. Mathematical functions
The following functions are defined in MATLAB
6.1. Trigonometric functions
Those known to Matlab are sin, cos, tan and their arguments should be in radians.
9
sin( ) - Sine.
sinh( ) - Hyperbolic sine.
asin( ) - Inverse sine.
asinh( ) - Inverse hyperbolic sine.
cos( ) - Cosine.
cosh( ) - Hyperbolic cosine.
acos( ) - Inverse cosine.
acosh( ) - Inverse hyperbolic cosine.
tan( ) - Tangent.
tanh( ) - Hyperbolic tangent.
atan( ) - Inverse tangent.
atanh( ) - Inverse hyperbolic tangent.
sec( ) - Secant.
sech( ) - Hyperbolic secant.
asec( ) - Inverse secant.
asech( ) - Inverse hyperbolic secant.
csc( ) - Cosecant.
csch( ) - Hyperbolic cosecant.
acsc( ) - Inverse cosecant.
acsch( ) - Inverse hyperbolic cosecant.
cot( ) - Cotangent.
coth( ) - Hyperbolic cotangent.
acot( ) - Inverse cotangent.
acoth( ) - Inverse hyperbolic cotangent.
>> x =5*cos(pi/6), y = 5*sin(pi/6)
x=
4.3301
y=
2.5000
The inverse of trigonometric functions are called asin, acos, atan (as opposed to the
usual arcsin or sin 1 etc.).
The result is in radians.
>> acos(x/5), asin(y/5)
ans =
0.5236
ans =
0.5236
10
Note: Matlab uses radian scale to calculate trigonometric functions. In other words,
sin(90) is not equal to 1, but sin(pi/2) is.
6.2. Exponential
These include sqrt, exp, log, log10
exp( ) - Exponential.
log( ) - Natural logarithm.
log10( ) - Common (base 10) logarithm.
sqrt( ) - Square root.
abs( ) - Absolute value.
Note: log( ) is ln in Matlab. To get logarithm in base 10, you must write log10( ).
>> exp(log(9)), log(exp(9))
ans =
9
ans =
9
Most common functions are available to Matlab
>>A=abs(-5), B=cos(3), C=exp(2), D=sqrt(4), E=log(40)
A=
5
B=
-0.9900
C=
7.3891
D=
2
E=
3.6889
6.3. Complex Number Functions
conj( ) - Complex conjugate.
Imag( ) - Complex imaginary part.
Real( ) - Complex real part.
>>A=2+4*i, B=conj(A), C=Imag(A), D=real(A)
A=
2.0000 + 4.0000i
B=
2.0000 - 4.0000i
11
C=
4
D=
2
7. Help
MATLAB is a huge package. You can’t learn everything about it at once, or always
remember how you have done things before. It is essential that you learn how to teach
yourself more using the online help.
If you need quick help on the syntax of a command, use help. For example, help
plot tells you all the ways in which you can use the plot command. (Of course, you have
to know already the name of the command you want.)
8. Closing Matlab
To close MATLAB type exit in the command window and next press Enter or Return
key. A second way to close your current MATLAB session is to select File in the
MATLAB's toolbar and next click on Exit MATLAB option. All unsaved information
residing in the MATLAB.
Workspace will be lost. You can also exit by typing:
>> quit
or
>> exit
To terminate a running Matlab command you may use [Ctrl]+[c] (Press both the Ctrl
button and the c button simultaneously).
12
9. Common commands
whos : gives a list of Matlab variables stored in the memory
clear : clears the memory
clear A : clears variable named A from the memory
clc : clears the command window
clf : clears the graphical window
The following example show how to assign values to variables, x and y.
>> x=sin(pi/4), y=log(2)
x=
0.7071
y=
0.6931
You can use who command to list the currently active variables. For the preceding
session this results in
>> who
Your variables are:
ans x y
Use clear command to delete variables from computer memory
>> clear x
>> x
??? Undefined function or variable 'x'.
Exercise 1:
Write a program to calculate the vapor pressure of water according to Antoine
equation: Po=exp(A-B/(T+C))
Where T is any given temperature in Kelvin and A, B, and C are Antoine
coefficients:
A=18.3036 B=3816.44 C= -46.13
13
Exercise 2:
Write a program to calculate the volumetric and mass flow rate of a liquid flowing in a
pipe with a velocity equal to 0.5 m/s. Knowing that the diameter of this pipe is 0.1 m and
the density of this liquid is 890 kg/m3 ?
Solution:
d=0.1;p=890;u=.5;
A=(pi/4)*d^2,Volflow=u*A,Massflow=Volflow*p
The result will be:
A=
0.0079
Volflow =
0.0039
Massflow =
3.4950
Exercise 3:
For the following distillation column write a code to find the value of stream B and
the compositions of stream D?
1) Use Matlab as a calculator to calculate the results of each of the following commands:-
Command Answer
7 + 8/2
7+8\2
(7+8)/2
4 + 5/3 +2
5^3/2
5^(10/5)
27^(1/3) + 32^0.2
27^1/3 + 32^0.2
6 25
b) * 3* 4
2 35
84 / 2
c) (3 1) 2
5 11
84
d) 3 2
2 2
2 * (5 11)
a) x 3 2 x 2 11
b) ( x 2) 2 8
( x 2) 2
c) 2
4
4) Define the variables a,b and c as: a=5, b=-5, and c=2a+b
Evaluate:
6a
a) ab ac
b
ca
b) a b / a
b ( a b ) / c
5) Compute the reaction rate constant for a first-order reaction given by the
Arrhenius law k=A e-E/RT, at a temperature T=500 K. Here the activation energy
is E=20 kcal/mol and the pre-exponential factor is A=1013 s-1. The ideal gas
constant is R=1.987 cal/mol K.
15
ALGEBRA
1. Symbolic Toolbox
One of the most powerful tools that can be used in Matlab is the “Symbolic
Toolbox”. To use Matlab’s facility for doing symbolic mathematics, it is necessary to
declare the variables to be “symbolic”. The best way to do that is to use the syms
declaration statement:
>>syms a b x y;
>>c = 5;
>>E = a*x^2 + b*x + c;
The syms statement makes all the variables listed with it into symbolic variables and
gives each of the variables a value that is equal to its own name. Thus, the value of a is a,
the value of b is b, etc. The variable E is now symbolic because it was assigned to be
equal to an expression that contained one or more symbolic variables. Its value is a*x^2 +
b*x + 5.
For example, suppose that you need factor x²-3x+2. Note that you must type 3*x for
3x. Then you type:
>> syms x
By syms you are declaring that x is a variable. Then type
>> factor(x^2-3*x+2)
ans =
(x-1)*(x-2)
To factor x2+2x+1, you write:
>> syms x
>> factor(x^2+2*x+1)
ans =
(x+1)^2
To factor the equation x2-y2;
>>syms x y
>> factor(x^2-y^2)
ans =
(x-y)*(x+y)
Expand command can be used to expand the terms of any power equation. Let's use
expand command to expand the following equation (x 2-y2)3.
>> expand((x^2-y^2)^3)
ans =
x^6-3*x^4*y^2+3*x^2*y^4-y^6
16
The simplify command is useful to simplify some equations like.
>> simplify((x^3-4*x)/(x^2+2*x))
ans =
x-2
2. Solving Equations
2.1 Algebraic Equations
By using Symbolic Toolbox, you can find solutions of algebraic equations with or
without using numerical values. If you need to solve equations, you can use the command
solve. For example, to find the solution of x3+x2+x+1=0 you write:
>> solve('x^3+x^2+x+1=0')
And Matlab give you the answer in the form
ans =
[ -1]
[ i]
[ -i]
That means the three solutions for the equation are 1, j, and –j.
>>x=solve('sin(x)+x=0.1')
x=
5.001042187833512e-2
In expressions with more than one variable, we can solve for one or more of the
variables in terms of the others. Here we find the roots of the quadratic ax2+bx+c in x in
terms of a, b and c. By default solve sets the given expression equal to zero if an
equation is not given.
>> x=solve('a*x^2+b*x+c','x')
x=
[ 1/2/a*(-b+(b^2-4*a*c)^(1/2))]
[ 1/2/a*(-b-(b^2-4*a*c)^(1/2))]
You can solve an equation in two variables for one of them. For example:
>> y=solve('y^2+2*x*y+2*x^2+2*x+1=0', 'y')
y=
[-x+i*(x+1)]
[ -x-i*(x+1)]
You can solve more than one equation simultaneously. For example to find the value
of x and y from the equations: 5x+10y=46 and 28x+32y=32, you write:
>> [x,y]=solve('5*x+10*y=46', '28*x+32*y=32')
17
And you get the following result:
x=
-48/5
y=
47/5
>> [x,y]=solve('log(x)+x*y=0', 'x*y+5*y=1')
x=
.8631121967939437
y=
.1705578823046945
To solve the system x²+ x+ y² = 2 and 2x-y = 2. We can type:
>> [x,y] = solve( 'x^2+ x+ y^2 = 2', '2*x-y = 2')
And get the solutions
x=
[ 2/5]
[ 1]
y=
[ -6/5]
[ 0]
This means that there are two points which are (2/5, -6/5) and (1, 0).
Now let's find the points of intersection of the circles x2+y2=4 and (x-1)2+(y-1)2=1.
>>[x,y]=solve('x^2+y^2=4','(x-1)^2+(y-1)^2=1')
x=
[ 5/4-1/4*7^(1/2)]
[5/4+1/4*7^(1/2)]
y=
[ 5/4+1/4*7^(1/2)]
[5/4-1/4*7^(1/2)]
In same way if you have more then two equations you can use the same command to
solve them for example:
[x,y,z]=solve('x+y+z=1','x+2*y-z=3','2*x-2*z=2')
x=
1/2
y=
1
z=
-1/2
18
2.2 DIFFERENTIAL EQUATIONS
2.2.1 First Order Differential Equations
Matlab can solve linear ordinary differential equations with or without
initial/boundary conditions. Do not expect Matlab can solve nonlinear ordinary differential
equations which typically have no analytical solutions. Higher derivatives can be handled
as well. The command for finding the symbolic solution of differential equations is dsolve.
For that command, the derivative of the function y is represented by Dy. For example,
suppose that we want to find the solution of the equation x y' - y = 1. We will have:
>> dsolve('x*Dy-y=1', 'x')
ans =
-1+x*C1
This means that the solution is any function of the form y = -1+ cx, where c is any
constant. The letter “D” has a special meaning and cannot be used otherwise inside dsolve.
It means “first derivative of”. The C1 is a constant of integration.
If we have the initial condition y(1) = 5, we can get the particular solution on the
following way:
>>dsolve('Dy+y=cos(t)')
ans =
1/2*cos(t)+1/2*sin(t)+exp(-t)*C1
>> dsolve('x*Dy-y=1', 'y(1)=5', 'x')
ans =
-1+6*x
19
Example: d2y/dx2 -2dy/dx -3y=x2
>> dsolve('D2y - 2*Dy - 3*y=x^2', 'x')
ans =
-14/27+4/9*x-1/3*x^2+C1*exp(3*x)+C2*exp(-x)
3. Representing Functions
There is a way to define functions in MATLAB that behave in the usual manner. To
represent a function in Matlab, we use “inline” command. For example to declare
f(x)=x2+3x+1 you write:
>> f=inline('x^2+3*x+1')
f=
Inline function:
f(x) = x^2+3*x+1
Therefore to find f(2), to get the answer you write:
>> f(2)
ans =
11
The function g(x,y)=x2-3xy+2 is defined as follows.
>> g=inline('x^2-3*x*y+2')
g=
Inline function:
g(x,y) = x^2-3*x*y+2
Now we can evaluate g(2,3) in the usual way.
>>g(2,3)
ans =
-12
In some cases, if we need to define function f as a vector. Then we use:
>> f = inline(vectorize('x^2+3*x-2'))
20
f=
Inline function:
f(x) = x.^2+3.*x-2
In this case, we can evaluate a function at more than one point at the same time. For
example, to evaluate the above function at 1, 3 and 5 we have:
>> f([1 3 5])
ans =
2 16 38
4. Differentiation
The Matlab function that performs differentiation is diff. These operations show how
it works:
>> syms x
>>diff(x^2)
ans =
2*x
>>diff(sin(x)^2)
ans =
2*sin(x)*cos(x)
For example, let's find the derivative of f(x)=sin(ex).
>> syms x
>> diff(sin(exp(x)))
and get the answer as:
ans =
cos(exp(x))*exp(x)
Note: Instead of using syms to declare of variables you can use two Quotes ' ' to
declare that the variable x is the interested variable in equation; you can use the same
example in otherwise
>>diff('sin(exp(x))')
ans =
cos(exp(x))*exp(x)
The nth derivative of f is in the written in the form diff(f,n). then to find the
second derivative we write;
>> diff(sin(exp(x)),2)
ans =
-sin(exp(x))*exp(x)^2+cos(exp(x))*exp(x)
For example to find the first derivative of x3+3x2+8x you simply write:
21
>> syms x
>> diff(x^3+3*x^2+8*x)
ans =
3*x^2+6*x+8
Moreover to get the 3rd derivative, write:
>> diff(x^3+3*x^2+8*x ,3)
ans =
6
Note: To get higher derivatives, you can write the degree in place of 3.
To compute the partial derivative of an expression with respect to some variable we
specify that variable as an additional argument in diff. For example to find the
derivative for x in equation f(x,y)=x3y4+ysinx.
>>syms x y
>> diff(x^3*y^4+y*sin(x),x)
ans =
3*x^2*y^4+y*cos(x)
Next we compute diff for y
>> diff(x^3*y^4+y*sin(x),y)
ans =
4*x^3*y^3+sin(x)
Finally we compute d3 fx3.
>> diff(x^3*y^4+y*sin(x),x,3)
ans =
6*y^4-y*cos(x)
5. Integration
By using the Symbolic Toolbox, you can find both definitive and in-definitive
integrals of functions. We can use MATLAB for computing both definite and indefinite
integrals using the command int. If f is a symbolic expression in x, then:
int(f) f ( x ) dx
For the indefinite integrals, consider the following example:
>> int('x^2')
ans =
1/3*x^3
Similarly as for diff command, we do not need the quotes if we declare x to be a
symbolic variable. Therefore the above command can be re-written in otherwise such as:
>> syms x
22
>> int(x^2)
ans =
1/3*x^3
For example to find the in-definitive integral of x3+sin(x), you write:
>> syms x
>> int(x^3+sin(x))
ans =
1/4*x^4-cos(x)
A definite integral can be taken by giving three arguments. The second and third
arguments in that case are the first and second limits of integration.
x b
int(f, a, b) x a f ( x)dx
For the definitive integrals:
>> int(x^2, 0, 1)
ans =
1/3
Try these examples,
int(x,1,2)
int(x*sin(x),-2,7)
Moreover to get definitive integral to ln(x)+1/(x+1) from x=1 to x=2 write, you
simply write:
>> int('ln(x) + 1/(x+1)', 1, 2)
ans =
log(6)-1
6. Limits
You can use limit to compute limits. For example, to evaluate the limit when x goes
to 2 of the function (x2-4)/(x-2),we have:
>> syms x
>> limit((x^2-4)/(x-2), x, 2)
ans =
4
Limits at infinity:
>> limit(exp(-x^2-5)+3, x, Inf)
ans =
3
23
Exercise 1:
For the mixer shown below write a code to find the values of streams A, B and C?
W= 100 Kg/hr
100% Benzene
A= ? B= ?
50% Xylene 30% Xylene
20% Toluene 30% Toluene
30% Benzene 40% Benzene
C= ?
40% Xylene
20% Toluene
40% Benzene
Solution: By making component material balance on each component within the
mixer you can reach to a system of three equations which can be solve by using the
command solve to find the unknowns A, B, C.
Type the following command:
[A,B,C]=solve('.5*A+.3*B=.4*C','.2*A+.3*B=.2*C','.3*A+.4*B+100=.4*C')
The results will be:
A=
600
B=
200
C=
900
Exercise 2:
For the following distillation column calculate the values of F1, F3 and F4?
F3=?
50%A
F1=? 30%B
20%A 20%D
30%B
50%D
F2=500 F4=?
50%A 20%A
50%B 40%B
40%D
24
Solution:
[F1,F3,F4]=solve('.2*F1+250=.5*F3+.2*F4','.3*F1+250=.3*F3+.4*F4','.5*F1=.
2*F3+.4*F4')
The results will be:
F1=
1000
F3=
500
F4 =
1000
Exercise 3:
Calculate the heat required to increase the temperature of 1 mol of methane from
533.15 K to 873.15 C at a pressure approximately 1 bar. where
Cp
A BT CT 2 DT 2
R
A=1.702 , B=9.081*10-3 , C=-2.164*10-6 , D=0 , R=8.314 and
Tout
Qn Cpdt
Tin
Solution:
syms T;
T1=533.15; T2=873.15;
A=1.702; B=9.081e-3; C=-2.164e-6; R=8.314;
Cp=(A+B*T+C*T^2);Q=R*int(Cp,T1,T2)
The results will be:
Q=
1.9778e+004
Exercise 4:
Evaluate the following double integral
sin x
0 0
(x 2 y 2 )dy dx
Solution: MATLAB can also do multiple integrals. The following command
computes the double integral:
syms x y;
int(int(x^2 + y^2, y, 0, sin(x)), 0, pi)
ans =
-32/9+pi^2
To convert the way of the result displaying, type the code:
single(-32/9+pi^2)
ans =
6.3140
25
Practice Problems
6) Write required code to solve each of the following:-
a) Factor x³+3x²y+3xy²+y³.
b) Simplify (x³-8)/(x-2).
c) Expand (x²+1)(x-5)(2x+3).
d) Solve sin x = 2-x for x.
e) Solve 5x+2y+4z = 8, -3x+y+2z = -7, 2x+y+z = 3 for x, y and z.
f) Solve y²-5xy-y+6x²+x = 2 for x.
g) Find the first derivative of the function (sinx/(ln(x2+1))-ex and evaluate it at
x=3.
h) Find the 12th derivative of the function (x/2+1)65
i) Find the first and second partial derivatives for x of the function ex2sinxy
7) Obtain the first and second derivatives of the following functions using
MATLAB’s symbolic mathematics.
a) F(x) = x5 – 8x4 + 5x3 – 7x2 + 11x – 9
b) F(x) = (x3 + 3x – 8)(x2 + 21)
c) F(x) = (3x3 – 8x2 + 5x + 9)/(x + 2)
d) F(x) = (x5 – 3x4 + 5x3 + 8x2 – 13)2
e) F(x) = (x2 + 8x – 11)/(x7 – 7x6 + 5x3 + 9x – 17)
26
Vectors
27
ans =
4.0000 7.0000 7.2361
>> v4 =3*v
v4 =
3.0000 9.0000 6.7082
>> v5 =2*v -3*v3
v5 =
-7.0000 -6.0000 -10.5279
We can build row vectors from existing ones:
>> w =[1 2 3], z = [8 9]
w=
1 2 3
z=
8 9
>> v6=[w z]
v6 =
1 2 3 8 9
A vector can be defined by previously defined vectors.
>> x = [2 4 -1]
x=
2 4 -1
>> x1 = [x 5 8 ]
x1 =
2 4 -1 5 8
An special array is the empty matrix, which is entered as [] .and can be used to
delete a part of any matrix or vector.
>> w=[4 5 6 7]
w=
4 5 6 7
>>w(4)=[];w
w=
4 5 6
The elements of a matrix can be defined with algebraic expressions placed at the
appropriate location of the element. Thus
>> a = [ sin(pi/2) sqrt(2) 3+4 6/3 exp(2) ]
a=
1.0000 1.4142 7.0000 2.0000 7.3891
28
2. Column Vectors
The column vectors have similar constructs to row vectors. When defining them,
entries are separated by ; or “newlines”.
Note how the column vector is defined, using brackets and semicolons to separate the
different rows. To define a column vector x:
x=[1; -2; 4]
x=
1
-2
4
or write
>>x=[1
2
3]
x=
1
-2
4
>> c =[ 1; 3; sqrt(5)]
c=
1.0000
3.0000
2.2361
3. Transposing
We can convert a row vector into a column vector (and vice versa) by a process
called transposing, denoted by '
> A=[ 1 2 3]
A=
1 2 3
>>B= A'
B=
1
2
3
29
4. Vectors Addition and subtraction
Addition and subtraction of a number to or from a vector can be made. In this case,
the number is added to or subtracted from all the elements of the vector. For example
>> x=[-1; 0; 2];
>> y=x-1
y=
-2
-1
1
If we look to make a simple addition and subtraction of vectors. The notation is the
same as found in most linear algebra. We will define two vectors then add or subtract
them:
>> v = [1; 2; 3]
v=
1
2
3
>> b = [2; 4; 6]
b=
2
4
6
>> v+b
ans =
3
6
9
>> v-b
ans =
-1
-2
-3
>> sin(v)
ans =
0.8415
0.9093
0.1411
30
>> log(v)
ans =
0
0.6931
1.0986
>> pi*v
ans =
3.1416
6.2832
9.4248
5. Vectors multiplication
Multiplication of vectors and matrices must follow special rules. In the example
above, the vectors are both column vectors with three entries. You cannot add a row vector
to a column vector. In the case of multiplication vectors, the number of columns of the
vector on the left must be equal to the number of rows of the vector on the right.
>> b = [2; 4; 6];
>> v = [1; 2; 3];
>> v*b
??? Error using ==> *
Inner matrix dimensions must agree.
>> v*b'
ans =
2 4 6
4 8 12
6 12 18
>> v'*b
ans =
28
6. element-wise operation
There are many times where we want to do an operation to every entry in a vector or
matrix. Matlab will allow you to do this with "element-wise" operations. For example,
suppose you want to multiply each entry in vector v with its corresponding entry in vector
b. In other words, suppose you want to find v(1)*b(1), v(2)*b(2), and v(3)*b(3). It would
be nice to use the "*" symbol since you are doing some sort of multiplication, but since it
31
already has a definition, we have to come up with something else. The programmers who
came up with Matlab decided to use the symbols ".*" to do this.
>> v.*b
ans =
2
8
18
Also for division we must use "./"
>> v./b
ans =
0.5000
0.5000
0.5000
Note that
v .* b multiplies each element of v by the respective element of b.
v ./ b divides each element of v by the respective element of b.
v .\ b divides each element of b by the respective element of v.
v .^ b raise each element of v by the respective b element.
32
>> t = 0:2:20
t=
0 2 4 6 8 10 12 14 16 18 20
>> m=0.32:0.1:0.6
m=
0.3200 0.4200 0.5200
>>w= -1.4:-0.3:-2
w=
-1.4000 -1.7000 -2.0000
The format is first:step:last. The result is always a row vector.
A negative step is also allowed. The command has similar results; it creates a vector
with linearly spaced entries.
There is another way to create row arrays is to use linspace functions:
>> A=linspace(1,2,5)
A=
1.0000 1.2500 1.5000 1.7500 2.0000
>> A=linspace(0,20,11)
A=
0 2 4 6 8 10 12 14 16 18 20
8. Referencing elements
It is frequently necessary to call one or more of the elements of a vector. Each
dimension is given a single index. Some examples using the definitions above:
Evaluate a vector A:
>> A=0:10:100
A=
0 10 20 30 40 50 60 70 80 90 100
Now after definition of a vector A, try to type:
>> A(10)
ans =
90
>> B=A(1:5)
B=
0 10 20 30 40
>> C=A(1:2:10)
C=
0 20 40 60 80
>> A(6:2:10)
33
ans =
50 70 90
Exercise 1:
Calculate Reynold Number at a diameter D=0.2 m, using different velocity's as
u=0.1,0.2,0.3 …1 m/s knowing that:
Re= (ρud)/µ , µ=0.001 , ρ =1000
Solution:
Type the code in the command window
d=0.2;
u=0.1:.1:1;
m=0.001;
p=1000;
Re=u*p*d/m
The results will be
Re =
1.0e+005 *
0.2000 0.4000 0.6000 0.8000 1.0000 1.2000 1.4000 1.6000
1.8000 2.0000
Exercise 2:
Estimate the average density of a Water/Ethanol mixture at different water
compositions knowing that.
Water density =1000 kg/m3
Ethanol density =780 kg/m3
Mixture density= Xwater × Water density + Xethanol × Ethanol density
Solution:
Pwater=1000;
Pethanol=780;
Xwater=0:.1:1
Xethanol=1-Xwater;
Pav=Pwater*Xwater+Pethanol*Xethanol
Xwater =
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000
0.8000 0.9000 1.0000
Pav =
780 802 824 846 868 890 912 934
956 978 1000
34
Practice Problems
1. Create a vector of the even whole numbers between 31 and 75.
3. Let x = [2 5 1 6].
a) Add 16 to each element.
b) Add 3 to just the odd-index elements.
c) Compute the square root of each element.
d) Compute the square of each element.
4. Let x = [3 2 6 8] and y = [4 1 3 5]
a) Add the elements in x to y
b) Raise each element of x to the power specified by the corresponding
element in y.
c) Divide each element of y by the corresponding element in x
d) Multiply each element in x by the corresponding element in y, calling the
result "z".
5. When A and B contain the values shown below, give the values of C vector after
executing the following statements.
A = [ 2 -1 5 0]; B = [3 2 -1 4]
a) C = A-B
b) C = B + A -3
c) C = B./A
d) C = A.^B
e) C = 2.^B+A
f) C = 2*A+A.^B
35
9. Other Operations on Vectors
MATLAB has a large number of built-in functions. You will only become familiar
with them by using them.
Try to make the vector v in command window and use the functions below.
v=[23 0 3 16 -8 13]
length(v) number of elements in v.
6
size(v) size of matrix v (raw, column).
1 6
find(v) finds indices of non-zero elements.
1 3 4 5 6
find(v==0) finds indices of elements equal to zero.
2
find(v==16) finds indices of elements equal to 16.
4
find(v>7) finds indices of elements greater than 7.
1 4 6
v(find(v>7)) finds the values of elements greater than 7.
23 16 13
sum(v) sum of elements
47
max(v) maximum element.
23
min(v) minimum element.
-8
mean(v) mean of elements.
7.8333
sort(v) sorts elements from minimum to maximum value.
-8 0 3 13 16 23
all(v) equal to 1 if all elements nonzero, 0 if any element nonzero.
0
abs(v) vector with absolute value of all element
23 0 3 16 8 13
36
Exercise 1:
Write a program to calculate average density, conductivity and specific heat for water
in the range of temperatures from 0 to 50 C . Knowing that this parameters for water are a
function of temperature such as the following equations.
The Density
= 1200.92 – 1.0056 TKo + 0.001084 * (TKo)2
The condactivity
K= 0.34 + 9.278 * 10-4 .TKo
The Specific heat
CP = 0.015539 (TKo – 308.2)2 + 4180.9
Note: take 11 point of temperatures
Solution:
T=[0:5:50]+273;
p= 1200.92 - 1.0056*T+ 0.001084 * T.^2;
Kc = 0.34 + 9.278 * 10^-4 *T;
Cp = 0.015539*(T - 308.2).^2 + 4180.9;
Average_density=mean(p)
Average_conductivity=mean(Kc)
Average_specificheat=mean(Cp)
Gives the results
Averagedensity =
997.7857
Averageconductivity =
0.6165
Averagespecificheat =
4.1864e+003
37
Interpolation is the same operation as table lookup. Described in table lookup terms,
the table is [x,y] and interp1 looks up the elements of xi in x, and, based upon their
locations, returns values yi interpolated within the elements of y.
Syntax
yi = interp1(x,y,xi)
where xi may be single element or a vector of elements.
Exercise 2:
The vapor pressures of 1-chlorotetradecane at several temperatures are tabulated here.
T (oC) 98.5 131.8 148.2 166.2 199.8 215.5
P*(mmHg) 1 5 10 20 60 100
o
Calculate the value of vapor pressure corresponding to 150 C?
Solution:
T= [98.5 131.8 148.2 166.2 199.8 215.5];
P= [1 5 10 20 60 100];
Pi=interp1 (T, P, 150)
The result will be:
Pi=
11.0000
Exercise 3:
The heat capacity of a gas is tabulated at a series of temperatures:
T (oC) 20 50 80 110 140 170 200 230
o
Cpj/mol. C 28.95 29.13 29.30 29.48 29.65 29.82 29.99 30.16
Calculate the values of heat capacity corresponding to 30, 70, 100 and 210 oC.
Solution:
T= [20 50 80 110 140 170 200 230];
P= [28.95 29.13 29.30 29.48 29.65 29.82 29.99 30.16];
Pv=interp1 (T, P, [30 70 100 210])
The results will be
Pv =
29.0100 29.2433 29.4200 30.0467
12. Roots
To calculate the roots of a polynomial, enter the coefficients in an array in descending
order. Be sure to include zeroes where appropriate.
For example to find the roots of the polynomial y= x 4 + 6x3 + 7x2 - 6x - 8 = 0 type
the command:
p = [ 1 6 7 -6 -8 ];
r = roots(p)
yields
r=
-4.0000
-2.0000
-1.0000
1.0000
Note: The coefficients could be entered directly in the roots command. The same
answer as above would be obtained using the following expression.
r = roots([ 1 6 7 -6 -8 ])
r=
-4.0000
1.0000
-2.0000
-1.0000
39
For example finding the roots of y=x4+3x3-15x2-2x+9=0 would be as easy as entering
the following command;
r=roots([1 3 -15 -2 9])
r=
-5.5745
2.5836
-0.7951
0.7860
The roots command can find imaginary roots.
p = [ 1 -6 18 -30 25 ];
r = roots(p)
r=
1.0000 + 2.0000i
1.0000 - 2.0000i
2.0000 + 1.0000i
2.0000 - 1.0000i
It can also find repeated roots. Note the imaginary portion of the repeated roots is
displayed as zero.
p = [ 1 7 12 -4 -16 ];
r = roots(p)
r=
-4.0000
-2.0000 + 0.0000i
-2.0000 - 0.0000i
1.0000
13. PolyVal
You can use polyval and the fitted polynomial p to predict the y value of the data
you've fitted for some other x values. The syntax for determining the value of a
polynomial y=x4 + 6x3 + 7x2 - 6x - 8 at any point is as follows.
p = [ 1 6 7 -6 -8 ];
y= polyval(p, 3)
y=
280
Where p is the vector containing the polynomial coefficients, (see above). Similarly,
the coefficients can be entered directly in the polyval command.
y = polyval([1 6 7 -6 -8], 3)
40
y=
280
The polynomial value at multiple points (vector) can be found.
z = [ 3 5 7];
y = polyval(p,z)
y=
280 1512 4752
14. Polyfit
To determining the coefficients of a polynomial that is the best fit of a given data you
can use polyfit command. The command is polyfit(x, y, n), where x, y are the data
vectors and 'n' is the order of the polynomial for which the least-squares fit is desired.
Exercise 4:
Fit x, y vectors to 3 rd order polynomial
x = [ 1.0 1.3 2.4 3.7 3.8 5.1 ];
y = [ -6.3 -8.7 -5.2 9.5 9.8 43.9 ];
coeff = polyfit(x,y,3)
coeff =
0.3124 1.5982 -7.3925 -1.4759
After determining the polynomial coefficients, the polyval command can be used to
predict the values of the dependent variable at each value of the independent variable.
ypred = polyval(coeff,x)
ypred =
-6.9579 -7.6990 -5.6943 8.8733 10.6506 43.8273
Its clear that there is a deviation between the actual y points and predicted y points
because that the polynomial is best fit to this actual points.
Exercise 5:
Fit the following data describing the accumulation of species A over time to a second
order polynomial, and then by using this polynomial, predict the accumulation at 15 hours.
Time (hr) 1 3 5 7 8 10
Mass A acc. 9 55 141 267 345 531
Solution: First, input the data into vectors, let:
a = [9, 55, 141, 267, 345, 531];
time = [1, 3, 5, 7, 8, 10];
Now fit the data using polyfit
41
coeff = polyfit(time,a,2)
coeff =
5.0000 3.0000 1.0000
So, Mass A = 5*(time)2 + 3 * (time) + 1
Therefore to calculate the mass A at 15 hours
MApred = polyval(coeff,15)
MApred =
1.1710e+003
Exercise 6:
Fit the following vapor pressure vs temperature data in fourth order polynomial. Then
calculate the vapor pressure when T=100 OC.
Temp (C) -36.7 -19.6 -11.5 -2.6 7.6 15.4 26.1 42.2 60.6 80.1
Pre. (kPa) 1 5 10 20 40 60 100 200 400 760
Solution:
vp = [ 1, 5, 10, 20, 40, 60, 100, 200, 400, 760];
T = [-36.7, -19.6, -11.5, -2.6, 7.6, 15.4, 26.1, 42.2, 60.6, 80.1];
p=polyfit(T,vp,4)
pre= polyval(p,100)
The results will be:
p=
0.0000 0.0004 0.0360 1.6062 24.6788
pre =
1.3552e+003
Exercise 7:
The calculated experimental values for the heat capacity of ammonia are:
T (C) Cp ( cal /g.mol C)
0 8.371
18 8.472
25 8.514
100 9.035
200 9.824
300 10.606
400 11.347
500 12.045
1. Fit the data for the following function
Cp a bT CT 2 DT 3
Where T is in C
2. Then calculate amount of heat Q required to increase the temperature of 150
42
mol/hr of ammonia vapor from 0 C to 200 C if you know that:
Tout
Q n Cpdt
Tin
Solution:
T=[0,18,25,100,200,300,400,500]
Cp=[8.371, 8.472, 8.514, 9.035, 9.824, 10.606, 11.347, 12.045]
P=polyfit(T,Cp,3)
n=150;
syms t
Cpf=P(4)+P(3)*t+P(2)*t^2+P(1)*t^3;
Q= n*int(Cpf, 0,200)
2.7180e+005
Practice Problems
1) Find the 3rd order polynomial that satisfies the data of water for saturation
temperature and pressure. By using the predicted polynomial compute the saturation
pressure at 65 C.
Temp(C) 0 10 20 30 40 50 60 70 80 90 100
Pre. (kPa) .6108 1.227 2.337 4.241 7.375 12.335 19.92 31.16 47.36 70.11 101.33
2) Write a MATLAB program to fit the following vapor pressure vs. temperature data
to calculate the values of constants A and B in following equation.
B
log( P 0 ) A
T 273 .15
Temp (C) -36.7 -19.6 -11.5 -2.6 7.6 15.4 26.1 42.2 60.6 80.1
Pre. (kPa) 1 5 10 20 40 60 100 200 400 760
3) The experimental velocity of an incompressible fluid in a pipe of radius 1 m is
tabulated as below:
r (m)
V
(m/s) r is the distance from the centre of the pipe and u is the velocity of the fluid.
Where:
Write a MATLAB program to fit the experimental velocity to the following function:
u=a+br+cr2
43
5) The rate at which a substance passes through a membrane is determined by the
diffusivity D,(cm2/s) of the gas. D varies with the temperature T (K) according to the
following law:
D = Doexp (-E /RT)
Where:
Do is the pre-exponential factor
E is the activation energy for diffusion
R =1.987 cal/mol K.
Diffusivities of SO2 in a certain membrane are measured at several temperatures with
the data listed below.
T(K) 347 374.2 396.2 420.7 447.7 471.2
D(cm2/s)×106 1.34 2.5 4.55 8.52 14.07 19.99
Write a MATLAB program to calculate the values of Do and E.
44