0% found this document useful (0 votes)
16 views

Introduction To Matlab

This document provides an introduction to using MATLAB for chemical engineering. It discusses topics like algebra, vectors, matrices, and mathematical functions in MATLAB. MATLAB can be used for matrix computations, solving systems of equations, integration, and other numerical computations. It describes the MATLAB interface and commands, variable types, arithmetic operations, formatting output, and predefined/mathematical functions available in MATLAB. The document is intended as an introductory guide for chemical engineering students learning to use MATLAB.

Uploaded by

thaer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Introduction To Matlab

This document provides an introduction to using MATLAB for chemical engineering. It discusses topics like algebra, vectors, matrices, and mathematical functions in MATLAB. MATLAB can be used for matrix computations, solving systems of equations, integration, and other numerical computations. It describes the MATLAB interface and commands, variable types, arithmetic operations, formatting output, and predefined/mathematical functions available in MATLAB. The document is intended as an introductory guide for chemical engineering students learning to use MATLAB.

Uploaded by

thaer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Computer Programming (II)

Computer Programming (II)


MATLAB for Chemical Engineer

Contents
1. Introduction to MATLAB
2. Algebra
3. Vectors
4. Interpolation
5. Polynomials in Matlab
6. Matrices
7. Matrix Algebra
8. Condition

References Books:
1. Rudra Pratap: Getting started with MATLAB 7, Oxford Press (Indian edition),2006.
2. Desmond J. Higham and Nicolas J. Higham: Matlab Guide, SIAM, 2000.
3. Duane Hanselman and Bruce Littlefield: Mastering Matlab 6:
A Comprehensive Tutorial and Reference, Prentice Hall, 2001.
4. Delores M. Etter: Engineering problem solving with Matlab, Prentice Hall,1993.
5. Schilling R. J., Harries S.L., Applied Numerical Methods for Engineers using
MATLAB & C,Thomson Books, 2002.

Web Sites:
1. Documentation from www.Mathworks.com
2. File exchange from www.matlabcentral.com
3. http://www.mathworks.com/access/helpdesk/help/techdoc/learn_matlab/
4. http://www.mathworks.com/academia/student_center/tutorials/

Second Class / Lec. 1 2


Computer Programming (II)

Introduction to MATLAB
MATLAB (MATrix LABoratory) is an interactive software system for numerical
computations and graphics. As the name suggests, MATLAB is especially designed for
matrix computations, solving systems of linear and nonlinear systems of equations,
integration of ordinary and partial differential equations, and many others.

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.

Second Class / Lec. 1 3


Computer Programming (II)

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.

1.2 The command window:

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.

This window allows a user to enter simple commands. To perform a simple


computations type a command and next press the Enter or Return key. For instance
>> s = 1 + 2
s=
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
Second Class / Lec. 1 4
Computer Programming (II)

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
(See Figure 3).

Figure 3: MATLAB Editor Window

1.3 Function Files


Function files are a special kind of script file (M-file) that allow you to define your
own functions for use during a Matlab session. You might think of them as subroutines
that can be called from within a script, or even called directly from the command line.
Many of the "built-in" functions in Matlab are actually stored as M-files as part of the
Matlab package. Function files are created and edited in identically the same manner as
the script files.

Second Class / Lec. 1 5


Computer Programming (II)

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
>>99.3-25
ans =
74.3000
>> 3*(23+14.7-4/6)/3.5
ans=
31.7429

Second Class / Lec. 1 6


Computer Programming (II)

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.

Second Class / Lec. 1 7


Computer Programming (II)

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

Second Class / Lec. 1 8


Computer Programming (II)

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

4.1 Predefined variables


There are several predefined variables which can be used at any time, in the same
manner as user defined variables (ans, pi, j):
I: sqrt(-1)
j: sqrt(-1)
pi: 3.1416...

For example,
>>pi
ans =
3.1416
>>j
ans =
0 + 1.0000i
>>y= 2*(1+4*j)
yields:
y=
2.0000 + 8.0000i

Second Class / Lec. 1 9


Computer Programming (II)

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.

Second Class / Lec. 1 10


Computer Programming (II)

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.
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

Second Class / Lec. 1 11


Computer Programming (II)

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
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

Second Class / Lec. 1 12


Computer Programming (II)

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
C=
4
D=
2

7. Help

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.).

>> help sin

Second Class / Lec. 1 13


Computer Programming (II)

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).

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'.

Second Class / Lec. 1 14


Computer Programming (II)

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
Solution: Let temperature equal to 373.15 k, write the following code.
T=373.15;
A=18.3036;B=3816.44;C= -46.13;
Pw=exp(A-B/(T+C))
The result will be:
Pw =
759.9430
Note: you can use any variable name in your code.

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

Second Class / Lec. 1 15


Computer Programming (II)

Exercise 3:
For the following distillation column write a code to find the value of stream B and
the compositions of stream D?

Solution: Type the commands as m-file. Then copy it to command window.


F=100;D=80;B=F-D
XF=0.15;SF=0.25;TF=0.4;ZF=0.2;
XB=0.15;SB=0.25;TB=0.4;ZB=0.2;
?% Z
XD=(F*XF-B*XB)/D*100
SD=(F*SF-B*SB)/D*100 D=80
TD=(F*TF-B*TB)/D*100?% X
?% S
?% T

ZD=(F*ZF-B*ZB)/D*100 F=100kg
Then after pressing enter the result will be:
B=
15% X
25% S
20
40% T
XD =
20% Z B=? 15% X
15
25% S
SD =
40% T
25 20% Z
TD =
40
ZD =
20

Second Class / Lec. 1 16


Computer Programming (II)

Practice Problems

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

2) Solve the following problems in command window


a) 37 82
5 2

25
b) 6 * 3 * 4
2 3 5

84 / 2
c) (3 1) 2
5 11

84
d) 32 2 2
2 * (5 11)

3) Define the variable x as x=6, then evaluate:

a) x 3 2 x 2 11
b) ( x 2) 2 8
2
c) ( x 2) 2
4

4) Define the variables a,b and c as: a=5, b=-5, and c=2a+b
Evaluate:
a) ab ac 6a
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=10 13 s-1. The ideal gas
constant is R=1.987 cal/mol K.

Second Class / Lec. 1 17

You might also like