Sunteți pe pagina 1din 65

MATLAB

Array and Matrix Operations


Cheng-Liang Chen
PSE
LABORATORY
Department of Chemical Engineering
National TAIWAN University
Chen CL 1
Matrix
Subscript and Index
Chen CL 2
Subscript and Index
A =
1st col 2nd col 3rd col 4th col 5th col
1st row 4
1
5
6
1
11
6
16
2
21
2nd row 8
2
2
7
9
12
4
17
7
22
3rd row 7
3
5
8
7
13
1
18
5
23
4th row 0
4
3
9
4
14
5
19
4
24
5th row 2
5
3
10
1
15
0
20
3
25
A(i, j) = A(i + (j 1)m) (stored as 1D vector, A : mn matrix)
A(2, 3) = A(12)
A(4 : 5, 2 : 3) = A([9 14; 10 15])
A(1 : 5, 5) = A(:, 5) = A(21 : 25) =
A(1 : end, end) = A(:, end) = A(21 : end)
Chen CL 3
Subscript and Index
A =
1st col 2nd col 3rd col 4th col 5th col
1st row 4
1
5
6
1
11
6
16
2
21
2nd row 8
2
2
7
9
12
4
17
7
22
3rd row 7
3
5
8
7
13
1
18
5
23
4th row 0
4
3
9
4
14
5
19
4
24
5th row 2
5
3
10
1
15
0
20
3
25
A(i, j) = A(i + (j 1)m) (stored as 1D vector, A : mn matrix)
A(2, 3) = A(12)
A(4 : 5, 2 : 3) = A([9 14; 10 15])
A(1 : 5, 5) = A(:, 5) = A(21 : 25) =
A(1 : end, end) = A(:, end) = A(21 : end)
Chen CL 4
Subscript and Index
A =
1st col 2nd col 3rd col 4th col 5th col
1st row 4
1
5
6
1
11
6
16
2
21
2nd row 8
2
2
7
9
12
4
17
7
22
3rd row 7
3
5
8
7
13
1
18
5
23
4th row 0
4
3
9
4
14
5
19
4
24
5th row 2
5
3
10
1
15
0
20
3
25
A(i, j) = A(i + (j 1)m) (stored as 1D vector, A : mn matrix)
A(2, 3) = A(12)
A(4 : 5, 2 : 3) = A([9 14; 10 15])
A(1 : 5, 5) = A(:, 5) = A(21 : 25) =
A(1 : end, end) = A(:, end) = A(21 : end)
Chen CL 5
Subscript and Index
A =
1st col 2nd col 3rd col 4th col 5th col
1st row 4
1
5
6
1
11
6
16
2
21
2nd row 8
2
2
7
9
12
4
17
7
22
3rd row 7
3
5
8
7
13
1
18
5
23
4th row 0
4
3
9
4
14
5
19
4
24
5th row 2
5
3
10
1
15
0
20
3
25
A(i, j) = A(i + (j 1)m) (stored as 1D vector, A : mn matrix)
A(2, 3) = A(12)
A(4 : 5, 2 : 3) = A([9 14; 10 15])
A(1 : 5, 5) = A(:, 5) = A(21 : 25) =
A(1 : end, end) = A(:, end) = A(21 : end)
Chen CL 6
Subscript and Index
A =
1st col 2nd col 3rd col 4th col 5th col
1st row 4
1
5
6
1
11
6
16
2
21
2nd row 8
2
2
7
9
12
4
17
7
22
3rd row 7
3
5
8
7
13
1
18
5
23
4th row 0
4
3
9
4
14
5
19
4
24
5th row 2
5
3
10
1
15
0
20
3
25
A(i, j) = A(i + (j 1)m) (stored as 1D vector, A : mn matrix)
A(2, 3) = A(12)
A(4 : 5, 2 : 3) = A([9 14; 10 15])
A(1 : 5, 5) = A(:, 5) = A(21 : 25) =
A(1 : end, end) = A(:, end) = A(21 : end)
Chen CL 7
Subscript and Index
A =
1st col 2nd col 3rd col 4th col 5th col
1st row 4
1
5
6
1
11
6
16
2
21
2nd row 8
2
2
7
9
12
4
17
7
22
3rd row 7
3
5
8
7
13
1
18
5
23
4th row 0
4
3
9
4
14
5
19
4
24
5th row 2
5
3
10
1
15
0
20
3
25
A(i, j) = A(i + (j 1)m) (stored as 1D vector, A : mn matrix)
A(2, 3) = A(12)
A(4 : 5, 2 : 3) = A([9 14; 10 15])
A(1 : 5, 5) = A(:, 5) = A(21 : 25) =
A(1 : end, end) = A(:, end) = A(21 : end)
Chen CL 8
One-Dimensional Array: Vector
>> g = [3, 7, 9]
g =
3
7
9
>> g = [3; 7; 9]
g =
3
7
9
>> g = [3
7
9]
g =
3
7
9
>> r = [2, 4, 20];
>> w = [9, -6, 3];
>> u = [r, w]
u =
2 4 20 9 -6 3
Chen CL 9
>> x = [0: 2: 8]
x =
0 2 4 6 8
>> x = [0: 2: 9]
x =
0 2 4 6 8
>> x = [8: -2: 0]
x =
8 6 4 2 0
>> x = [0: 4]
x =
0 1 2 3 4
>> x = linspace(0,8,5)
x =
0 2 4 6 8
>> x = logspace(-1, 1, 4)
x =
0.1000 0.4642 2.1544 10.000
% 4 equally-spaced pts 10^{-1}-10^{1}
Chen CL 10
Two-Dimensional Arrays: Matrix
A = [2, 4, 10; 16, 3, 7]
A =
2 4 10
16 3 7
a = [1, 3, 5]
a =
1 3 5
b = [7, 9, 11]
b =
7 9 11
c = [a b]
c =
1 3 5 7 9 11
d = [a; b]
d =
1 3 5
7 9 11
d = [[1, 3, 5]; [7, 9, 11]]
d =
1 3 5
7 9 11
Chen CL 11
Array Addressing
>> B = [ 2, 4,10,13;
16, 3, 7,18;
8, 4, 9,25;
3,12,15,17]
B =
2 4 10 13
16 3 7 18
8 4 9 25
3 12 15 17
>> C = B(2:3, 1:3)
C =
16 3 7
8 4 9
>> B(3,:) = []
B =
2 4 10 13
16 3 7 18
3 12 15 17
>> B([1 4],2:3) = 5
B =
2 5 5 13
16 3 7 18
3 12 15 17
0 5 5 0
>> B(2,6) = 6
B =
2 5 5 13 0 0
16 3 7 18 0 6
3 12 15 17 0 0
0 5 5 0 0 0
>> A = B(:,3:-1:1)
A =
5 5 2
7 3 16
15 12 3
5 5 0
>> D = A([2,2,2],:)
D =
7 3 16
7 3 16
7 3 16
Chen CL 12
Using clear to Avoid Errors
>> A = [2, 5; 6, 9];
>> x = [1:5];
>> A(:, 1) = x
----> error (row numbers in
A and x must be the same !)
>> A = [2, 5; 6, 9];
>> x = [1:5];
>> clear A
>> A(:, 1) = x
A =
1
2
3
4
5
Chen CL 13
Some Useful Array Functions
A = [6,2; -10,-5; 3,0]
x = max(A), y = min(A), ...
z = size(A),k = length(A)
A =
6 2
-10 -5
3 0
x = % max value of
6 2 % each column
y = % min value of
-10 -5 % each column
z =
3 2
k =
3
A = [6,2; -10,-5; 3+4i,0]
x = max(A), y = min(A), ...
z = size(A),k = length(A)
A =
6.0000 2.0000
-10.0000 -5.0000
3.0000 + 4.0000i 0
x = % max magnitude
-10 -5
y = % min magnitude
3.0000+4.0000i 0
z =
3 2
k =
3
Chen CL 14
Command Description
cat(n,A,B,C,...) Creates a new array by concatenating A,B,... along dimension n
nd(x) Computes an array containing indices of nonzero elements of array x
[u,v,w]=nd(A) Computes arrays u,v containing row and column indices of nonzero elements of matrix A, and the
array w containing values of nonzero elements. (w may be omitted)
length(A) Computes either the number of elements of A if A is a vector or the largest value of m or n if A is
an mn matrix
linspace(a,b,n) Creates a row vector of n equally spaced values between a and b
logspace(a,b,n) Creates a row vector of n logarithmically spaced values between a
and b
max(A) Returns a row vector containing largest element in each column of A
[x,k] = max(A) Stores max(A) in x and indices in k
min(A) Same as max(A) but returns minimum values
[x,k] = min(A) Stores min(A) in x and indices in k
size(A) Returns a row vector [m n] containing the sizes of the mn array
sort(A) Sorts each column of array A in ascending order and returns an array the same size as A
sum(A) Sums the elements in each column of array A and returns a row vector containing the sums
Chen CL 15
Test Your Understanding
T2.1-1 For the matrix B, nd the array that results from the
operation [B; B

]. Use MATLAB to determine what number is in


row 5, column 3 of the result.
B =
_

_
2 4 10 13
16 3 7 18
8 4 9 25
3 12 15 17
_

_
T2.1-2 For the same matrix B, use MATLAB to (a) nd the
largest and smallest element in B and their indices and (b) sort
each column in B to create a new matrix C.
Chen CL 16
Multi-dimensional Arrays
A = [4, 6, 1;
5, 8, 0;
3, 9, 2];
A(:,:,2) = [6, 2, 9;
0, 3, 1; 4, 7, 5]
A(:,:,1) =
4 6 1
5 8 0
3 9 2
A(:,:,2) =
6 2 9
0 3 1
4 7 5
A = [8, 2; 9, 5];% 2x2
B = [4, 6; 7, 3];% 2x2
C = cat(1,A,B); %C=[A;B]
D = cat(2,A,B); %D=[A,B]
E = cat(3,A,B); %E(:,:,1)=A
C, D, E %E(:,:,2)=B
C =
8 2
9 5
4 6
7 3
D =
8 2 4 6
9 5 7 3
E(:,:,1) =
8 2
9 5
E(:,:,2) =
4 6
7 3
Chen CL 17
Array (Element-by-Element) Operations
Symbol Operation Form Example
+ Scalar-array addition A+b [6,3]+ 2 =[8, 5]
- Scalar-array subtraction A-b [6,3]- 2 =[4, 1]
+ Array addition A+B [6,3]+[3,8] =[9,11]
- Array subtraction A-B [6,3]-[3,8] =[3,-5]
.* Array multiplication A.*B [3,2].*[2,4]=[6, 8]
./ Array right division A./B [4,8]./[2,4]=[2, 2]
.\ Array left division A.\B [2,4].\[4,8]=[2, 2]
.^ Array exponent A.^B [3,5].^2 =[9,25]
2.^[3,5] =[8,32]
[3,2].^[2,3]=[9, 8]
Chen CL 18
Example: Vectors and Relative Velocity
A train is heading east at 60 miles per hour. A car approaches the track crossing
at 45 miles per hour on a road that makes a 55
o
angle with the track. What is the
velocity of the train relative to the car ? What is the speed of the train relative to
the car ?
Solution:
The trains velocity v
R
relative to the car is the dierence between the trains
velocity relative to the ground v
T
and the cars velocity relative to the ground v
C
v
R
= v
T
v
C
Choosing the x direction to be east, and y north,
v
T
= 60i + 0j
v
C
= 45 cos(55
o
)i + 45 sin(55
o
)j
= 25.8109i + 36.8618j
v
R
= v
T
v
C
= 34.1891i 36.8618j (miles/hour) (south-east)
s
R
=
_
(34.1891)
2
+ (36.8618)
2
= 50.2761 (miles/hour)
Chen CL 19
v_T = [60, 0];
v_C = [45*cos(55*pi/180), 45*sin(55*pi/180)];
v_R = v_T - v_C;
s_R = sqrt(v_R(1)^2+v_R(2)^2);
v_T, v_C, v_R, s_R
v_T =
60 0
v_C =
25.8109 36.8618
v_R =
34.1891 -36.8618
s_R =
50.2761
Chen CL 20
Example: Vectors and Displacement
Suppose two divers start at the surface and establish the following coordinate
system: x is to the west, y is to the north, and z is down. Diver 1 swims 55 feet
west, 36 feet north, and then dive 25 feet. Diver 2 dives 15 feet, then swims east
20 feet and then north 59 feet.
1. Find the distance between diver 1 and the starting point.
2. How far in each direction must diver 1 swim to reach diver 2 ?
3. How far in a straight line must diver 1 swim to reach diver 2
Solution:
diver 1: v
1
= 55i + 36j + 25k
diver 2: v
2
= 20i + 59j + 15k
dist 10: dist
10
=

55
2
+ 36
2
+ 25
2
= 70.3278
v
12
= v
2
v
1
= 75i + 23j 10k
dist 12: dist
12
=
_
(75)
2
+ 23
2
+ (10)
2
= 79.0822
Chen CL 21
v_10 = [ 55, 36, 25];
v_20 = [-20, 59, 15];
v_12 = v_20 - v_10;
ss_10 = 0; ss_12 = 0;
for k = 1:3
ss_10 = ss_10 + v_10(k)^2;
ss_12 = ss_12 + v_12(k)^2;
end
dist_10 = sqrt(ss_10);
dist_12 = sqrt(ss_12);
v_12, dist_10, dist_12
v_10 = [ 55, 36, 25];
v_20 = [-20, 59, 15];
v_12 = v_20 - v_10;
dist_10 = sqrt(sum(v_10.*v_10));
dist_12 = sqrt(sum(v_12.*v_12));
v_12, dist_10, dist_12
v_12 =
-75 23 -10
dist_10 = 70.3278
dist_12 = 79.0822
Chen CL 22
Example: Aortic Pressure Model
Biomedical engineers often design instrumentation to measure physiological
processes, such as blood pressure. To do this they must develop mathematical
models of the process. The following equation is a specic case of one model used
to describe the blood pressure in the aorta during systole (the period following the
closure of the hearts aortic valve). The variable t represents time in seconds, and
the dimentionless variable y represents the pressure dierence across the aortic
valve, normalized by a constant reference pressure. Plot this function for t 0.
y(t) = e
8t
sin
_
9.7t +

2
_
Solution:
Frequency = 9.7 radians/second = 9.7/(2) = 1.5 cycles/second
Period = 1/1.5 = 2/3 second
select a spacing of 0.003 to give approximately 200 points per period
t = 0 e
0
= 1
t = 0.5 e
8(0.5)
= 0.02
select upper limit of t to be 0.5 second
Chen CL 23
t = [0 : 0.1 : 0.5];
y_1 = exp(-8*t);
y_2 = sin(9.7*t+pi/2);
y = y_1.*y_2;
p = [t; y_1; y_2; y]
p =
0 0.1000 0.2000 0.3000 0.4000 0.5000
1.0000 0.4493 0.2019 0.0907 0.0408 0.0183
1.0000 0.5653 -0.3609 -0.9733 -0.7395 0.1372
1.0000 0.2540 -0.0729 -0.0883 -0.0301 0.0025
t = [0 : 0.003 : 0.5];
y = exp(-8*t).*sin(9.7*t+pi/2);
plot(t,y), xlabel(t (sec)),...
ylabel(Normalized Pressure Difference y(t))
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5
0.2
0
0.2
0.4
0.6
0.8
1
1.2
t (sec)
N
o
r
m
a
l
i
z
e
d

P
r
e
s
s
u
r
e

D
i
f
f
e
r
e
n
c
e

y
(
t
)
Chen CL 24
Example: Transportation Route Analysis
The following table gives data for the distance traveled along ve truck routes and
the corresponding time required to traverse each route. Use the data to compute
the average speed required to drive each route. Find the route that has the
highest average speed.
1 2 3 4 5
Distance (miles) 560 440 490 530 370
Time (hours) 10.3 8.2 9.1 10.1 7.5
>> d = [ 560, 440, 490, 530, 370];
>> t = [10.3, 8.2, 9.1, 10.1, 7.5];
>> speed = d./t
>> [highest_speed, route] = max(speed)
speed =
54.3689 53.6585 53.8462 52.4752 49.3333
highest_speed =
54.3689
route =
1
Chen CL 25
Example: Current and Power Dissipation
The current i passing through an electrical resistor having a voltage v across it is
given by Ohms law: i = v/R, where R is the resistance. The power dissipated in
the resistor is given by v
2
/R. The following table gives data for the resistance and
voltage for ve resistors. Use the data to compute (a) the current in each resistor
and (b) the power dissipated in each resistor.
1 2 3 4 5
R (ohms) 10
4
2 10
4
3.5 10
4
10
5
2 10
5
v (volts) 120 80 110 200 350
>> R = [10000, 20000, 3500, 100000, 200000];
>> v = [ 120, 80, 110, 200, 350];
>> current = v./R
current =
0.0120 0.0040 0.0314 0.0020 0.0018
>> power = v.^2./R
power =
1.4400 0.3200 3.4571 0.4000 0.6125
Chen CL 26
Example: A Batch Distillation Process
Chemical and environmental engineers must sometimes design batch processes for
producing or purifying liquids and gases. Applications of such processes occur in
food and medicine production, and in waste processing and water purication. An
example of such a process is a system for heating a liquid benzene/toluene
solution to distill a pure benzene vapor. A particular batch distillation unit is
charged initially with 100 mol of a 60% mol benzene/40% mol toluene mixture.
Let L (mol) be the amount of liquid remaining in the still, and let x (mol B/mol)
be the benzene mole fraction in the remaining liquid. Conservation of mass for
benzene and toluene can be applied to derive the following relation (Felder, 1986).
L = 100
_
x
0.6
_
0.625
_
1 x
0.4
_
1.625
Determine what mole fraction of benzene remains when L = 70. Note that it is
dicult to solve this equation directly for x. Use a plot of x versus L to solve the
problem.
Chen CL 27
>> x = [0 : .001 : 0.6];
>> L = 100*(x/0.6).^(0.625).*((1-x)/0.4).^(-1.625);
>> plot(L,x), grid, xlabel(L (mol)), ylabel(x (mol B/mol)),...
>> set(gca, xtick, [0 10 20 30 40 50 60 70 80 90 100]);
>> [L,x] = ginput(1)
L =
69.9616
x =
0.5271
0 10 20 30 40 50 60 70 80 90 100
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
L (mol)
x

(
m
o
l

B
/
m
o
l
)
Chen CL 28
Example: Height versus Velocity
In introductory physics courses Newtons laws of motion are used to derive the
following formula for the maximum height h achieved by an object thrown with a
speed v at an angle to the horizon.
h =
v
2
sin
2

2g
Create a table showing the maximum height for the following values of v and :
v = 10, 12, 14, 16, 18, 20 meters/sec = 50
o
, 60
o
, 70
o
, 80
o
Chen CL 29
g = 9.8; v = [10:2:20]; th = [50:10:80]; thr = th*(pi/180);
vel = [];
for k = 1:length(th)
vel = [vel, v]; % [v v v v]
end
theta = [];
for k = 1:length(v) % thr
theta = [theta;thr]; % ...
end % thr
h = vel.^2.*sin(theta).^2/(2*g);
H = [v, h];
table = [0, th; H] % table = [0 th; v h]
table =
0 50.0000 60.0000 70.0000 80.0000
10.0000 2.9940 3.8265 4.5052 4.9482
12.0000 4.3114 5.5102 6.4875 7.1254
14.0000 5.8682 7.5000 8.8302 9.6985
16.0000 7.6646 9.7959 11.5334 12.6674
18.0000 9.7006 12.3980 14.5969 16.0322
20.0000 11.9760 15.3061 18.0209 19.7928
Comparison:
Chen CL 30
g = 9.8;
v = [10: 2: 20];
th = [50:10:80];
thr = th*(pi/180);
vel = [];
for k = 1:length(th)
vel = [vel, v];
end
theta = [];
for k = 1:length(v)
theta = [theta;thr];
end
h = vel.^2.*sin(theta).^2/(2*g);
table = [0 th; v h]
g = 9.8;
v = [10: 2: 20];
th = [50:10:80];
thr = th*(pi/180);
[theta vel] = meshgrid(thr, v);
h = vel.^2.*sin(theta).^2/(2*g);
table = [0 th; v h]
g = 9.8;
v = [10: 2: 20];
th = [50:10:80];
thr = th*(pi/180);
for i = 1:length(v)
for j = 1:length(thr)
h(i,j) = v(i)^2*sin(thr(j))^2/(2*g);
end
end
table = [0 th; v h]
Chen CL 31
Test Your Understanding
T2.3-1 Given the matrices
A =
_
_
21 27
18 8
_
_
B =
_
_
21 27
18 8
_
_
nd their (a) array product, (b) array right division (A divided by
B), and (c) B raised to the third power element by element.
(ANS: (a) [147, 81, 162, 32], (b) [3, 9, 2, 2], (c)
[343, 27; 729, 64])
Chen CL 32
Matrix Operations
i = [1 0 0]

j = [0 1 0]

k = [0 0 1]

i i = j j = k k = 1
i j = j k = k i = 0
u = u
1
i + u
2
j + u
3
k w = w
1
i + w
2
j + w
3
k
u w = (u
1
i + u
2
j + u
3
k) (w
1
i + w
2
j + w
3
k)
= u
1
w
1
+ u
2
w
2
+ u
3
w
3
=
_
u
1
u
2
u
3
_
_

_
w
1
w
2
w
3
_

_
_
a
11
a
12
a
21
a
22
__
x
1
x
2
_
=
_
a
11
x
1
+ a
12
x
2
a
21
x
1
+ a
22
x
2
_
_
a
11
a
12
a
21
a
22
__
b
11
b
12
b
21
b
22
_
=
_
a
11
b
11
+ a
12
b
21
a
11
b
12
+ a
12
b
22
a
21
b
11
+ a
22
b
21
a
21
b
12
+ a
22
b
22
_
Chen CL 33
Test Your Understanding
T2.4-1 Use MATLAB to compute the dot product of the following
vectors:
u = 6i 8j + 3k
w = 5i + 3j 4k
Check your answer by hand. (ANS: -6)
T2.4-1 Use MATLAB to show that
_

_
7 4
3 2
5 9
_

_
_
_
1 8
7 6
_
_
=
_

_
35 80
11 12
68 94
_

_
Chen CL 34
Example: Manufacturing Cost Analysis
The following table shows the hourly cost of four types of manufacturing
processes. It also shows the number of hours required of each process to produce
three dierent products. (a) Determine the cost of each process to produce one
unit of product 1. (b) Determine the cost to make one unit of each product. (c)
Suppose we produce 10 units of product 1, 5 units of product 2, and 7 units of
product 3. Compute the total cost.
Hours required to produce one unit
Process Hourly cost ($) Product 1 Product 2 Product 3
Lathe 10 6 5 4
Grinding 12 2 3 1
Milling 14 3 2 5
Welding 9 4 0 3
Chen CL 35
>> hourly_cost = [10, 12, 14, 9];
>> hours_1 = [6, 2, 3, 4];
>> hours_2 = [5, 3, 2, 0];
>> hours_3 = [4, 1, 5, 3];
>> process_cost_1 = hourly_cost.*hours_1
process_cost_1 =
60 24 42 36
>> unit_cost = hourly_cost*[hours_1, hours_2, hours_3]
unit_cost =
162 114 149
>> units = [10, 5, 7];
>> total_cost = units*unit_cost
total_cost =
3233
Chen CL 36
Example: Product Cost Analysis
The following tables show the costs associated with a certain product, and the
production volume for the four quarters of the business year. Find the quarterly
costs for materials, labors, and transportation; the total material, labor, and
transportation costs for the year; and the total quarterly costs.
Unit Costs ($ 10
3
)
Product Materials Labor Transportation
1 6 2 1
2 2 5 4
3 4 3 2
4 9 7 3
Product Quarter 1 Quarter 2 Quarter 3 Quarter 4
1 10 12 13 15
2 8 7 6 4
3 12 10 13 9
4 6 4 11 5
Chen CL 37
>> U = [6,2,1; 2,5,4; 4,3,2; 9,7,3];
>> P = [10,12,13,15; 8,7,6,4; 12,10,13,9; 6,4,11,5];
>> C = U*P, ...
>> Quarterly_Costs = sum( U*P), ...
>> Category_Costs = sum((U*P))
C =
178 162 241 179 %178: material cost in Q1
138 117 172 112 %138: labor cost in Q1
84 72 96 64 % 84: transportation cost in Q1
Quarterly_Costs =
400 351 509 355
Category_Costs =
760 539 316
Chen CL 38
Special Matrices
Command Description
eye(n) Creates an n n identity matrix
eye(size(A)) Creates an identity matrix with the same size of A
ones(n) Creates an n n matrix of ones
ones(m,n) Creates an mn array of ones
ones(size(n)) Creates an array of ones with the same size of A
zeros(n) Creates an n n matrix of zeros
zeros(m,n) Creates an mn array of zeros
zeros(size(n)) Creates an array of zeros with the same size of A
Chen CL 39
Polynomials
f(x) = 9x
3
5x
2
+ 3x + 7 g(x) = 0x
3
+6x
2
x + 2
f(x) + g(x) = 9x
3
+ x
2
+ 2x + 9
f(x)g(x) = 54x
5
39x
4
+ 41x
3
+ 29x
2
x + 14
f(x)
g(x)
= 1.5x 0.5833
>> f = [9, -5, 3, 7]; g = [6, -1, 2]; g0 = [0, 6, -1, 2];
>> summation = f + g0
summation =
9 1 2 9
Chen CL 40
>> product = conv(f, g)
product =
54 -39 41 29 -1 14
>> [quotient, remainder] = deconv(f, g)
quotient =
1.5000 -0.5833
remainder =
0 0 -0.5833 8.1667
>> a = [9, -5, 3, 7];
>> x = [0: 2: 10];
>> f = polyval(a, x), ...
>> g = polyval([9, -5, 3, 7], [0: 2: 10])
f =
7 65 515 1789 4319 8537
g =
7 65 515 1789 4319 8537
Chen CL 41
Polynomial Functions
Command Description
conv(a,b) Computes product of two polynomials (need not
be the same degree)
[q, r]=deconv(num,den) Computes dividing of two polynomials
poly(r) Computes coecients of the polynomial whose
roots are specied by vector r
polyval(a,x) Evaluates a polynomial at specied values of x
roots(a) Computes the roots of a polynomial (result is a
column vector)
Chen CL 42
Example: Earthquake Resistant Building
Buildings designed to withstand earthquakes must
have natural frequencies of vibration that are not
close to the oscillation frequency of the ground
motion. A buildings natural frequencies are
determined primarily by the masses of its oors
and by the lateral stiness of its surrounding
columns (which act like horizontal springs). We
can nd these frequencies by solving for the
roots of a polynomial called the structures
characteristic polynomial.
For a three-story building, if each oor has a mass m and the columns have
stiness k, the polynomial is
( f
2
)[(2 f
2
)
2

2
] +
2
f
2
2
3
where = k/4m
2
. The buildings natural frequencies in cycles per second are
the positive roots of this equation. Find the buildings natural frequencies
(cycles/second) for the case where m = 1000 kg and k = 5 10
6
newtons per
meter.
Chen CL 43
k = 5e+6; m = 1000;
alpha = k/(4*m*pi^2);
p1 = [-1, 0, alpha];
p2 = [-1, 0, 2*alpha];
p3 = [alpha^2, 0, -2*alpha^3];
p4 = conv(p2, p2) - [0, 0, 0, 0, alpha^2];
p5 = conv(p1, p4);
p6 = p5 + [0, 0, 0, 0, p3];
r = roots(p6)
pos = r(r>0)
r =
20.2789
-20.2789
14.0335
-14.0335
5.0085
-5.0085
pos =
20.2789
14.0335
5.0085
Chen CL 44
Test Your Understanding
T2.5-1 Use MATLAB to conrm that
(20x
3
7x
2
+ 5x + 10)(4x
2
+ 12x 3)
= 80x
5
+ 212x
4
124x
3
+ 121x
2
+ 105x 30
T2.5-2 Use MATLAB to conrm that
12x
3
+ 5x
2
2x + 3
3x
2
7x + 4
= 4x + 11
T2.5-3 Use MATLAB to conrm that
6x
3
+ 4x
2
5
12x
3
7x
2
+ 3x + 9
= 0.7108
when x = 2.
Chen CL 45
Cell Array Functions
Function Description
c = cell(n) Creates an n * n cell array c of empty matrices
c = cell(n,m) Creates an n * m cell array c of empty matrices
celldisp(c) Displays the contents of cell array c
cellplot(c) Displays a graphical representation of the cell
array c
c = num2cell(A) Converts a numeric array A into a cell array c
[X,Y, ...] = deal(A,B, ...) Matches up the input and output lists. Equivalent
to X = A, Y = B,...
[X,Y, ...] = deal(A) Matches up the input and output lists. Equivalent
to X = A, Y = A,...
iscell(C) Returns a 1 if C is a cell array; otherwise, returns
a 0
Chen CL 46
Example: An Environmental Database
Data collection is important for early detection of change in our environment. In
order to detect such changes, we need to be able to analyze the database
eciently, and this eort requires a database that is set up for easy access. As a
simple example, suppose you want to create a 2 2 cell array A, whose cells
contain the location, that data, the air temperature (measured at 8 A.M., 12
noon, and 5 P.M.), and the water temperatures measured at the same time in
three dierent points in a pond. The cell array looks like the following.
Walden Pond June 13, 1997
[60 72 65]
_

_
55 57 56
54 56 55
52 55 53
_

_
Chen CL 47
Example: An Environmental Database
Solution:
Create an array
A(1,1) = {Walden Pond};
A(1,2) = {June 13, 1997};
A(2,1) = {[60, 72, 65]};
A(2,2) = {[55, 57, 56; 54, 56, 55; 52, 55, 53]};
Content Indexing:
A{1,1} = Walden Pond;
A{1,2} = June 13, 1997;
A{2,1} = [60, 72, 65];
A{2,2} = [55, 57, 56; 54, 56, 55; 52, 55, 53];
Chen CL 48
Example: An Environmental Database
Type A at the command line:
A =
Walden Pond June 13, 1997
[1*3 double] [3*3 double]
Typing celldisp(A) displays
A{1,1} =
Walden Pond
A{2,1} =
60 72 65
.
.
etc.
Chen CL 49
Example: An Environmental Database
Typing cellplot(A) to see this display for cell array A
Use commas or spaces with braces to indicate columns of cells and use semicolons
to indicate rows of cells
B = {[2,4], [6,-9;3,5]; [7;2], 10};
Create the following 2 2 cell array:
[2 4]
_
6 9
3 5
_
[7 2] 10
Chen CL 50
Accessing Cell Array
One can access the contents of a cell array by using either cell
indexing or content indexing
C = cell(3,5) % prelocate empty cell array with specified size
C(2,4) = {[6, -3,7]}; % put 1x3 array in cell (2,4)
C(1,5) = {1:10}; % put numbers 1-10 in cell (1,5)
C(3,4) = {30 mph} % put one string in cell (3,4)
% cell indexing
Speed = C(3,4) % place contents of cell(3,4) in new variable
D = C(1:3, 2:5) % place cont.s in rows 1-3, col.s 2-5 in cell D
% a new cell array D
% content indexing
Speed = C{3,4} % assign contents 30 mph to variable Speed
deal function accesses elements of a range of cells in a cell array
[x,y] = deal(B{2,:})
x = y =
7 2 10
Chen CL 51
Using Cell Array
Use cell arrays in comma-separated lists
H = {[2,4,8], [6,-8,3], [2:6], [9,2,5]};
The expression H{2:4} is equivalent to a comma-separated list of the second
through fourth cells in H
To create a numeric array J from the rst, second, and fourth cells in the cell
array H
J = [H{1}; H{2}; H{4}]
The result is:
J =
_

_
2 4 8
6 8 3
9 2 5
_

_
Chen CL 52
Using Cell Array
Typing H{2:3} displays the arrays in second and third cells
>>H{2:3}
ans =
6 -8 3
ans =
2 3 4 5 6
Chen CL 53
Using Cell Array
Use cell arrays in function input and output lists
>>[K{1:2}] = max(J)
K =
[1x3 double] [1x3 double]
>> K{1} % to see the maximum value
ans =
9 4 8
>> K{2}
ans =
3 1 1
Chen CL 54
Using Cell Array
Apply functions and operators to cell contents
L = {[2,4,8], [6,-8,3]; [2:6], [9.2.5]; [1,4,5], [7,5,2]};
max(L{3,2})
ans =
7
Nested cell arrays have cells that contain cell arrays
N(1,1) = {2,7,5};
N(1,2) = {{[5,9,1]; 4,8,0], Case 1; {5,8}, [7,3]}};
N
N =
[1x3 double] {2x2 cell}
Chen CL 55
Using Cell Array
Following steps create the same array N using the cell function
% FIrst create an empty 1x2 cell array
N = cell(1,2)
% Then create a 2x2 cell array inside N(1,2)
N(1,2) = {cell(2,2)}
% Then fill N using assignment statement
N(1,1) = {[2,7,5]};
N{1,2}(1,1) = {[5,9,1; 4,8,0]}
N{1,2}(1,2) = {Case 1}
N{1,2}{2,1}(1) = {5}
N{1,2}{2,1}(2) = {8}
N{1,2}(2,2) = {[7,3]}
Chen CL 56
Using Cell Array
Final example:
H = {[2,4,8], [6,-8.3]; [2,6], [9.2.5]; [1,4,5], [7,5,2]};
J = [H{1,1}; H{1,2}; H{2,2}];
J =
2 4 8
6 8 3
9 2 5
H{2:3, :}
ans =
2 3 4 5 6
ans =
9 2 5
ans =
1 4 5
ans =
7 5 2
Chen CL 57
Test Your Understanding
T2.6-1
Create the following cell array:
A = {[1:4], [0, 9, 2], [2:5], [6:8]}
What is B = A{1:2} ?
What is C = [A{2}; A{4}] ?
What is D = min(A{2:3}) ?
Chen CL 58
Structure Arrays
Example: A Student Database
Assignment of data in the structure array student
Create a structure array to contain the following types of student data:
Student name
Social Security number
Email address
Test scores
Enter the data into the database.
Chen CL 59
Create the structure and start with data for the rst student
student.name = John Smith;
student.SSN = 392-77-1786;
student.email = smithj@myschool.edu;
student.tests = [67, 75, 84];
Type student
>> student
name: John Smith
SSN: = 392-77-1786
email: = smithj@myschool.edu
tests: = [67 75 84]
Chen CL 60
To add a second student
student(2).name = Mary Jones;
student(2).SSN = 431-56-9832;
student(2).email = jonesm@myschool.edu;
student(2).tests = [84, 78, 93];
Type student again
>> student =
1x2 struct array with fields:
name
SSN
email
tests
Chen CL 61
Obtain information about the elds by using eldnames
>> fieldnames(student)
ans =
name
SSN
email
tests
To build a structure array named sa_1
sa_1 = struct(field1,values1,field2,values2,...)
student = struct(name,John Smith, SSN,392-77-1786,...
email,smithj@myschool.edu, tests,[67,75,84])
Modifying structures
student(1).phone = 555-1653
Chen CL 62
Structure Functions
Function Description
names = eldnames(S) Returns the eld names associated with the structure array S as names,
a cell array of strings
F = geteld(S,eld) Returns the contents of the eld eld in the structure array S.
Equivalent to F = S.eld
iseld(S,eld) Returns 1 if eld is the name of a eld in the structure array S, and 0
otherwise
isstruct(S) Returns 1 if the array S is a structure array, and 0 otherwise
S = rmeld(S,eld) Removes the eld eld from the structure array S
S = seteld(S,eld,V) Sets the contents of the eld eld to the value V in the structure
array S
S = struct(f1,v1,f2,v2,...) Creates a structure array with the elds f1, f2, . . ., having the values
v1, v2, . . .
Chen CL 63
Test Your Understanding
T2.7-1
Created the structure array student shown in Figure 2.7-1 and add
the following information about a third student:
name: Alfred E. Newman;
SSN: 555-12-3456;
e-mail: newmana@myschool.edu;
tests: 55,45,58.
T2.7-2
Edit your structure array to change Mr.Newmans second test score
from 45 to 53.
T2.7-1
Edit your structure array to remove the SSN eld.
Chen CL 64
Thank You for Your Attention
Questions Are Welcome

S-ar putea să vă placă și