MATLAB 1
MATLAB 1
Chemical Engineering
CHE 247
Introduction
3
MATLAB Introduction
Matlab Windows
4
MATLAB Introduction
workspace
Command window
5
Working in the command window
6
MATLAB arithmetic operations with scalars
7
Selected display formats
Command Example Description
format short >>290/7 => 41.4286 Fixed point with 4 decimal digits
10
Topic 2
MATLAB as Calculator
11
Problem 1: Simple mathematical expression
13
Creating Arrays in Matlab
▪ The array is a fundamental form that MATLAB uses
to store and manipulate data
▪ An ARRAY is a list of numbers arranged in ROWS
and COLUMNS
▪ ARRAYS are characterized by their DIMENSIONS.
▪ VECTOR is ONE dimensional ARRAY
▪ Matrix is a TWO dimensional ARRAY
▪ ARRAYS can have higher dimensions
▪ VECTORS are ROW or COLUMN vectors
▪ Data in the ARRAYS are NUMBERS or
CHARACTERS
14
Creating Arrays in Matlab
Enter a statement like following in matlab command window
and press entre
16
Creating Arrays in Matlab
17
Array operations
Equally spaced data can also be generated using
following command
18
Array operations
• Array Addressing and Selecting Array Elements
a= [ 1 2 3 4]
a (3) 3rd element will be displayed
In Matlab, index arrays inside of parenthesis are used to
select elements of an array. The colon operator is used
to select an entire row or column.
19
Class Practice
Create one dimensional array within range of 1 to 100 with
step of
a. 1
b. 0.5
c. 2.5
d. 10
20
Built in functions
Generate data using linspace command within 0 to 10 and try following
built-in functions
1. mean(x)
2. max(x)
3. min(x)
4. sort(x)
5. median(x)
6. std(x)
7. rand
8. rand(2,2) rand(rows, columns)
9. rand(2,4)
10. rand(3)
11. randperm(5)
12. randperm(5,3)
21
Creating 2-dimensional array
a=[1 2 3 ; 4 5 6; 7 8 9];
a=[(1:1:3); linspace(4,5,3) ; 7 8 9];
22
Creating 2-dimensional array
a=[1 2 3 ; 4 5 6; 7 8 9]
a=[(1:1:3); linspace(4,5,3) ; 7 8 9]
a=zeros (rows, columns) (create zero vector of given
size of rows and columns)
b = [ 5 4 6; 7 8 9; 1 2 3]
b(:,:) both column and rows will be displayed
b(1,:) elements of 1st rows will be displayed
b(:,3) elements of 3rd column will be displayed
24
Array operations
b(:,[1 3]) elements of 1st and 3rd column will be displayed.
b(5) 5th element will be displayed
diag(b) elements of diagonal will be displayed
Demonstration using MATLAB
25
Changing and Deleting Array Elements
Elements can be changed by selecting a portion of an array as
the left-hand-side target of an assignment statement:
For example, if
a=[1 2 3 4 5]
a(2) may be replaced with 10 using following command
a(2) = 10
>> a=[1:1:5];
>> a(1,3)=0 Replace 3rd element of 1st row with zero
a=
1 2 0 4 5
>> a([1,3])=0
Replace 1st and 3rd element with zero
a=
0 2 0 4 5
26
Changing and Deleting Array Elements
27
Manipulating Arrays
Transpose
Transpose of A = A’
fliplr(A) (Flip left/right)
flipud(A) (Flip up/down)
28
Some built in functions
• length(a)
• size(a)
• reshape(a,m,n)
• diag(v)
– More from help in Elementary Matrix and
Matrix Manipulation
29
Multiplication and addition
• Scalars A scalar can be added to or multiplied with each
element of an array; e.g.,
A = [1 3 4 5 7 8 ]
for 2 + A
ans will be ans= 3 5 6 7 9 10
30
Multiplication and addition
31
Multiplication and addition
Arrays are multiplied together in two different ways:
▪ matrix multiplication, where the inner dimensions of the arrays
must be the same
▪ element-by-element multiplication, indicated by the use of a
dot (.) along with the operator, where the arrays must have
compatible sizes
32
Multiplication and addition
33
Array division
▪ If AB=BA=I then
▪ B is inverse of A and A is inverse of B and I is an
identity matrix
▪ All A, B, and I are square matrices
Inverse of A = A^(-1) or inv(A)
▪ LEFT division \ : to solve matrix equation AX=B
In matlab X=A\B
or X = inv(A)*B
▪ In MatLab X= A\B
▪ RIGHT division “/” is used to solve XC=D where X and
D are ROW vectors
X= D/C
34
Array determinant
35
Linear Algebra Solution
4 −2 6 𝑥 8
2 8 2 𝑦= 4
6 10 3 𝑧 2
36
Summation
The elements of a single array can be added
together using the sum and cumsum functions
sum(a) Vector summation or each column of matric is summed up.
37
Strings and string variables
▪ ‘abc’ is a string
▪ ‘a256cc’ or ‘matlab’ or ‘3%abc’ are all strings
▪ Used
▪ to display text messages
▪ In formatting commands of plots
▪ Input argument of some functions
▪ A=‘this is a string’
▪ A=‘the numbers are 50 out of 100’
38
Concept of simple script file
39
Concept of simple script file
Find the vapor pressure of water using Antoine equation within
temperature range of 293 to 373 K.
40
Output: Disp and fprintf commands
The disp statement
The general form of disp for a numeric variable is
disp( variable )
Command Purpose
disp Displays contents of an array or string.
format Controls screen-display format.
42
fprintf command
43
Class activity
Find the vapor pressure of water using Antoine equation within
temperature range of 293 to 373 K.
44
fprintf to save output to a file
45
fprintf to save output to a file
46
Class Activity
1: Solve the set of linear equations
2x - 12y = 0
2x + 8y + 2z = 8 X=inv(A)*B
6x +10y + 3z = 1
Find the values of x,y and z.
2: generate an array x (0-2pi) and apply cos(x),
sin(x)
Note: command to convert degrees to radians in MATLAB is deg2rad(x)
or sind(x),cosd(x) or define x in form of pi.
3: generate an array and take mean, standard
deviation, summation, maximum, minimum and
median. Also sort the data in ascending and
descending order.
47
Vectors: summary
48
Vectors: summary
49
Matrices: summary
50
Matrices: summary
51
Plotting and concept of script files
52
2D Plotting
▪ Plot
▪ Axis labels
▪ Scale
▪ Titles
Elements of 2D plot
▪ Legend
▪ Text
▪ Line style
▪ Marker
53
2D Plotting: Elements of 2D plot
▪ Plot command is used to plot graph
between two variables x and y.
plot(x,y)
54
2D Plotting: Elements of 2D plot
55
2D Plotting: Elements of 2D plot
x=[0:5:360];
y=sind(x);
z=cosd(x);
plot(x,y,'k-')
hold on
title('trignometric functions in 4th semester class
CHE247')
xlabel('angle in degrees/(units)')
ylabel('sinx')
plot(x,y,'g-')
56
2D Plotting: Line specifiers
57
2D Plotting: Line color specifiers
Red r Magenta m
Green g Yellow y
Blue b Black k
Cyan c White w
58
2D Plotting: Element of graph
title('title')
xlabel('xlabel')
ylabel('xlabel')
xlim([minimum value max-value])
ylim([minimum value max-value])
legend(‘string1’, 'string2’)
axis equal
axis square
59
2D Plotting: axis
xlim([minimum value max-value])
ylim([minimum value max-value])
axis equal
axis square
axis tight
axis normal
grid on
grid off
60
2D Plotting: Element of graph
61
Plotting multiple graphs
plot (x,y,x,z)
or use the command of hold on and plot multiple
graphs on same figure
62
Class Activity
x=[0:5:360];
y=sind(x);
z=cosd(x);
plot(x,y,'--g','LineWidth',2,'MarkerSize',10,...
'MarkerEdgeColor','b')
xlabel('angle')
ylabel('sinx')
hold on
plot(x,z,'r','LineWidth',4,'MarkerSize',3,...
'MarkerEdgeColor','g')
legend('sinx','cosx')
63
Class Activity
x=linspace(0,1,100);
64
Semi log and log-log plots
• semilogy(x,y)
• semilogx(x,y)
• loglog(x,y)
• Caution
– Log of 0 does not exist
– Log of –ve number is complex
65
Try other common plots
• bar(x,y)
• barh(x,y)
• stairs(x,y)
• stem(x,y)
• pie(x)
• hist(x)
66
Class Practice
69
Subplot (m,n,p)
Subplot (m,n,p)
(2,3,1) (2,3,2) (2,3,3)
Subplot(2,3,1), plot(x,y)
Subplot(2,3,2), plot(x,y)
70
Demonstration in the class
Lab Assignment-WFT-1a
71
Lab Assignment-WFT-1b
72
Explore 3D-plotting
Commands used for 3D plotting are
1. plot3(x,y,z)
2. surf(x,y,z)
73
3D-plot
plot3(x,y,z)
74
Polynomial equation
75
Polynomial equation
76
Polynomial equation
77
Polynomial equation-summary
78
Lab practice
[1 9 28 38 24]
79
Pressure of a gas using a cubic equation
80
Solution
clear, clc
%Pressure of toluene gas using van der Waals equation of state
n=0.25; %kmol
V=0.55; %m3
T=350; %oC
T=T+273.15; %K
Tc=591.75; %K
pc=4108; %kPa
R=8.3145; %m3.kPa/(kmol.K)
a=(27/64)*(R^2)*(Tc^2)/pc; %m6.kPa/kmol2
b=(R*Tc)/(8*pc); %m3/kmol
v=V/n; %m3/kmol
p=((R*T)/(v-b))-(a/(v^2)) %kPa
83
fzero, fsolve, and roots built-in functions
function y=f1(x)
y=x^2+3*x+2;
pc = 7374; %kPa 85
Tc = 304.12; %K
Density of CO2 using a cubic equation of state
%Density of CO2 using RK EoS
p = 5000; %kPa
T = 450; %K
R = 8.3145; %kPa.m3/(kmol.K)
pc = 7374; %kPa
Tc = 304.12; %K
M = 44.01; %kg/kmol
v_ig = (R*T)/p; %m3/kmol
den_ig = (p*M)/(R*T) %kg/m3
a = 0.42747*(R^2)*(Tc^2)/pc; %m6.kPa/lmol2
b = 0.08664*R*Tc/pc; %m3/kmol
alpha = sqrt(Tc/T);
fV_RK= @(v) v^3-(R*T/p)*(v^2)+((a*alpha/p)-(b*R*T/p)-(b^2))*v-(a*alpha*b/p);
v = fzero(fV_RK,v_ig); %m3/kmol
den = M/v
86
Solution using roots
clear, clc
%Problem 6: Density of CO2 using RK EoS
p = 5000; %kPa
T = 450; %K
R = 8.3145; %kPa.m3/(kmol.K)
pc = 7374; %kPa
Tc = 304.12; %K
M = 44.01; %kg/kmol
v_ig = (R*T)/p; %m3/kmol
den_ig = (p*M)/(R*T) %kg/m3
a = 0.42747*(R^2)*(Tc^2)/pc; %m6.kPa/lmol2
b = 0.08664*R*Tc/pc; %m3/kmol
alpha = sqrt(Tc/T);
Pe = [1, -(R*T/p), ((a*alpha/p)-(b*R*T/p)-(b^2)), -(a*alpha*b/p)];
v=roots(Pe); %m3/kmol
v=max(v)
den = M/v %kg/m3
87
Assignment-FTW2
88
Home Practice: inv, linsolve, and fsolve built-in
functions
89
Basic Statics and curve
fitting
90