CH 4
CH 4
MATLAB
MATRICES
1. Defining Matrices
You can define a matrix by typing in a list of numbers enclosed in square brackets. You
can separate the numbers by commas or by spaces or combine the two techniques in the
same matrix definition. To indicate a new row, you can use a semicolon:
If there are too many numbers in a row to fit on one line, you can continue the statement
on the next line, but a comma and an ellipsis (…) are required at the end of the line,
indicating that the row is to be continued.
a=[2, 4, 8, 26, 197, 3, 90, 38, 28, 221, 234, 15, 97, 83, 90];
or
a=[2, 4, 8, 26, 197, 3, 90, 38, 28, ...,
221, 234, 15, 97, 83, 90];
You can define a matrix in terms of another matrix that has already been defined.
a=[1, 4, 12], b=[2, 6, 9], c=[a; b]
→ c=
1 4 12
2 6 9
If we define element a(9) = 1.4; matrix a will have eight values, and the values of a(5),
a(6), a(7), and a(8) will be set to 0
a(9)=1.4 → a=[2, 3, 4, 5, 0, 0, 0, 0, 1.4]
P a g e | 29
2. Extracting data from matrices
x=(r1:r2, c1:c2) extracts from row r1 to r2 and from column c1 to column c2 from a
matrix a.
x=a(1:3, 2:4)
→x =
3 4 5
7 6 5
5 -2 1
P a g e | 30
3. Special Matrices
zeros(m): Creates an m×m matrix of zeros.
a=zeros(2) → a = 0 0
0 0
P a g e | 31
diag(a)For any vector a, creates a square matrix with a as the diagonal.
a=[-2, 4, 7] b=diag(a)
→b =
-2 0 0
0 4 0
0 0 7
a= magic(3) → a= 8 1 6
3 5 7
4 9 2
a=[2,7; 5,3;9,7;-3,1]
b=a' → b=
2 5 9 -3
7 3 7 1
P a g e | 32
(^) matrix power.
Note:
Raising a matrix c to the matrix power (^)of two is different from raising c to the array
power (.^) of two.
c.^2=
9.0000 25.0000 4.0000
49.0000 5.7600 1.6900
30.2500 36.0000 7.8400
OR c = a^-1
d = inv(b)
→ d =??? Error using ==> inv Matrix must be square.
P a g e | 33
5. Solution of Linear equations
Given:
x = inv(A)*r
a=[2,3,-2;-1,-1,-1;1,-2,3], r=[-5;-4;13]
x = A\r
a=[2,3,-2;-1,-1,-1;1,-2,3], r=[-5;-4;13]
x = a\r → x=
2.0000
-1.0000
3.0000
P a g e | 34
c. Solution Using the Reduced Row Echelon Function
rref(b)
a=[2,3,-2;-1,-1,-1;1,-2,3], r=[-5;-4;13]
b = [2, 3, -2, -5; -1, -1, -1, -4; 1, -2, 3, 13]
rref(b) →
1 0 0 2
0 1 0 -1
0 0 1 3
a=[3,2,5;4,5,-2;1,1,1;2,-4,-7], r=[22;8;6;-27]
x=a\r →
1.0000
2.0000
3.0000
If the system is underdefined then MATLAB solves the problem by setting some variables
equal to zero.
a=[2,5,3;6,12,8], r=[18;8]
→ ans =
-29.3333
15.3333
0
a=[3,2,5,7;4,5,-2,3], r=[20;12]
→ ans =
0
0.8276
0
2.6207
P a g e | 35