0% found this document useful (0 votes)
36 views67 pages

Lecture2 CAED

The document discusses variables, vectors, and matrices in MATLAB, including how to define scalar and array variables to store values, and how vectors and matrices are arrays that can hold multiple values in 1D or 2D form. It also covers useful commands for creating, manipulating, and performing operations on vectors and matrices.

Uploaded by

Qamar Sultana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views67 pages

Lecture2 CAED

The document discusses variables, vectors, and matrices in MATLAB, including how to define scalar and array variables to store values, and how vectors and matrices are arrays that can hold multiple values in 1D or 2D form. It also covers useful commands for creating, manipulating, and performing operations on vectors and matrices.

Uploaded by

Qamar Sultana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Lecture 2: Variables, Vectors

and Matrices in MATLAB


Variables in MATLAB
• Just like other programming >> A = 5
A =
languages, you can define 5
variables in which to store
values. >> d = 7
d =
• All variables can by default 7
hold matrices with scalar or
complex numbers in them. >> LightSpeed = 3e8
LightSpeed =
• You can define as many 300000000
variables as your PC memory
can hold.
• Values in variables can be
inspected, used and changed
• Variable names are case-
sensitive, and show up in the
Workspace.

2
Variables
• You can change the >> a = 7
a =
7
value in the variable by
>> b = 12
over-writing it with a b =
12
new value >> b = 14
b =
• Remember that variables 14

are case-sensitive (easy >> B = 88


B =
88
to make a mistake)
>> c = a + b
• Always left-to right c =
21

>> variable = expression >> c = a / b


c =
0.5000

3
Exercise
• Develop MATLAB
code to find Cylinder
volume and surface
area.
• Assume radius of 5 m
and height of 13 m.

ܸ = ߨ‫ ݎ‬2 ℎ
‫ = ܣ‬2ߨ‫ ݎ‬2 + 2ߨ‫ݎ‬ℎ = 2ߨ‫ݎ‬ሺ‫ ݎ‬+ ℎሻ
4
Solution
>> r = 5
r =
5

>> h = 13
h =
13

>> Volume = pi * r^2 * h


Volume =
1.0210e+003

>> Area = 2 * pi * r * (r + h)
Area =
565.4867
5
Useful MATLAB commands

6
Vectors and Matrices (Arrays)
• So far we used MATLAB variables to
store a single value.
• We can also create MATLAB arrays that
hold multiple values
– List of values (1D array) called Vector
– Table of values (2D array) called Matrix
• Vectors and matrices are used
extensively when solving engineering
and science problems.
7
Row Vector
• Row vectors are special cases of matrices.
• This is a 7-element row vector (1 × 7 matrix).
• Defined by enclosing numbers within square
brackets [ ] and separating them by , or a space.
>> C = [10, 11, 13, 12, 19, 16, 17]

C =
10 11 13 12 19 16 17

>> C = [10 11 13 12 19 16 17]

C =
10 11 13 12 19 16 17

8
Column Vector
• Column vectors are special cases of matrices.
• This is a 7-element column vector (7 × 1 matrix).
• Defined by enclosing numbers within [ ] and
separating them by semicolon ;
>> R = [10; 11; 13; 12; 19; 16; 17]

R =
10
11
13
12
19
16
17

9
Matrix
• This is a 3 × 4-element matrix.
• It has 3 rows and 4 columns (dimension 3 × 4).
• Spaces or commas separate elements in different columns,
whereas semicolons separate elements in different rows.
• A dimension n × n matrix is called square matrix.

>> M = [1, 3, 2, 9; 6, 7, 8, 1; 7, 4, 6, 0]
M =
1 3 2 9
6 7 8 1
7 4 6 0

>> M = [1 3 2 9; 6 7 8 1; 7 4 6 0]
M =
1 3 2 9
6 7 8 1
7 4 6 0
10
Transpose of a Matrix
• The transpose operation interchanges the rows and
columns of a matrix.
• For an m × n matrix A the new matrix AT (read
“A transpose”) is an n × m matrix.
• In MATLAB, the A’ command is used for transpose.

11
Exercise
>> A = [1 2 3; 5 6 7] >> B = [5 6 7 8]
A = B =
1 2 3 5 6 7 8
5 6 7
>> B'
>> A' ans =
ans = 5
1 5 6
2 6 7
3 7 8

• What happens to a row vector when transposed?


• What happens to a column vector when transposed?

12
Useful Functions
length(A) Returns either the number of elements of A if A
is a vector or the largest value of m or n if A is an
m × n matrix
size(A) Returns a row vector [m n] containing the
sizes of the m × n matrix A.
max(A) For vectors, returns the largest element in A.
For matrices, returns a row vector containing the
maximum element from each column.

[v,k] = max(A) Similar to max(A) but stores the maximum


values in the row vector v and their indices in
the row vector k.
min(A) Like max but returns minimum values.
and
[v,k] = min(A)
13
More Useful Functions

sort(A) Sorts each column of the array A in ascending


order and returns an array the same size as A.
sort(A,DIM,MODE) Sort with two optional parameters:
DIM selects a dimension along which to sort.
MODE is sort direction ('ascend' or 'descend').
sum(A) Sums the elements in each column of the array A
and returns a row vector containing the sums.
sum(A,DIM) Sums along the dimension DIM.

14
Exercises
>> M = [1 6 4; 3 7 2]
>> X = [4 9 2 5]
X = >> size(M)
4 9 2 5
>> length(M)
>> length(X)
ans = >> max(M)
4
>> [a,b] = max(M)
>> size(X)
ans =
>> sort(M)
1 4

>> min(X)
>> sort(M, 1, 'descend')
ans =
2 >> sum(M)

>> sum(M, 2)

15
Solution
>> M = [1 6 4; 3 7 2]
M = >> sort(M)
1 6 4 ans =
3 7 2 1 6 2
3 7 4
>> size(M)
ans = >> sort(M, 1, 'descend')
2 3 ans =
3 7 4
>> length(M) 1 6 2
ans =
3 >> sum(M)
ans =
>> max(M) 4 13 6
ans =
3 7 4 >> sum(M, 2)
ans =
>> [a,b] = max(M) 11
a = 12
3 7 4
b =
2 2 1
16
The Variable Editor [from
Workspace or openvar('A')]

17
Creating Big Matrices
• What if you want to create a Matrix that
contains 1000 element (or more)?
• Writing each element by hand is difficult,
time-consuming and error-prone.
• MATLAB allows simple ways to quickly
create matrices, such as:
• Using the colon : operator (very popular).
• Using linspace() and logspace()
functions (less popular, but useful).
18
Using the colon operator
• MATLAB command X = J:D:K creates vector
X = [J, J+D, ..., J+m*D] where m = fix((K-J)/D).
• In other words, it creates a vector X of values
starting at J, ending with K, and with spacing D.
• Notice that the last element is K if K - J is an
integer multiple of D. If not, the last value is less
than J.
• MATLAB command J:K is the same as J:1:K.
• Note:
– J:K is empty if J > K.
– J:D:K is empty if D == 0, if D > 0 and J > K, or if
D < 0 and J < K.

19
Example 1
>> x = 0:2:8
x =
0 2 4 6 8

>> x = 0:2:7
x =
0 2 4 6

>> x = 4:7
x =
4 5 6 7

>> x = 7:2
x =
Empty matrix: 1-by-0

20
Example 2
>> x = 7:-1:2
x =
7 6 5 4 3 2

>> x = 5:0.1:5.9
x =
Columns 1 through 5
5.0000 5.1000 5.2000 5.3000 5.4000

Columns 6 through 10
5.5000 5.6000 5.7000 5.8000 5.9000

>> y = 5:0.1:5.9; % what happened here?!


>>
>> % now create a ‘column’ vector from 1 to 10 using :

21
Alternatives to colon
• linspace command creates a linearly spaced row
vector, but instead you specify the number of
values rather than the increment.
• The syntax is linspace(x1,x2,n), where x1 and
x2 are the lower and upper limits and n is the
number of points.
• If n is omitted, the number of points defaults to 100.
• logspace command creates an array of
logarithmically spaced elements.
• Its syntax is logspace(a,b,n), where n is the
number of points between 10a and 10b.
• If n is omitted, the number of points defaults to 50.
22
Exercise

>> x = linspace(5,8,3)

x =

5.0000 6.5000 8.0000

>> x = logspace(-1,1,4)

x =

0.1000 0.4642 2.1544 10.0000

23
Special: ones, zeros, rand
>> a = ones(2,4)
a =
1 1 1 1
1 1 1 1

>> b = zeros(4, 3) % null matrix


b =
0 0 0
0 0 0
0 0 0
0 0 0

>> c = rand(2, 4)
c =
0.8147 0.1270 0.6324 0.2785
0.9058 0.9134 0.0975 0.5469

% random values drawn from the standard


% uniform distribution on the open
% interval(0,1)
24
>> eye(4) % identity matrix
ans =
1 0 0 0 Null and
0 1 0 0
0
0
0
0
1
0
0
1
Identity
>> A = [1 2 3; 4 5 6; 7 8 9]
A =
Matrix
1 2 3
4 5 6
7 8 9

>> I = eye(3)
I =
1 0 0
0 1 0
0 0 1

>> A*I
ans =
1 2 3
4 5 6
7 8 9
25
Matrix Determinant & Inverse
>> A = [1 2 3; 2 3 1; 3 2 1]
A =
1 2 3
2 3 1
3 2 1

>> det(A) % determinant


ans =
-12

>> inv(A) % inverse


ans =
-0.0833 -0.3333 0.5833
-0.0833 0.6667 -0.4167
0.4167 -0.3333 0.0833

>> A^-1
ans =
-0.0833 -0.3333 0.5833
-0.0833 0.6667 -0.4167
0.4167 -0.3333 0.0833

26
Accessing Matrix Elements
>> C = [10, 11, 13, 12, 19, 16, 17]

C =
10 11 13 12 19 16 17

>> C(4)
ans =
12

>> C(1,4)
ans =
12

>> C(20)
??? Index exceeds matrix dimensions.

27
Notes
• Use () not [] to access matrix elements.
• The row and column indices are NOT zero-
based, like in C/C++.
• The first is row number, followed by the
column number.
• For matrices and vectors, you can use one of
three indexing methods: matrix row and
column indexing; linear indexing; and logical
indexing.
• You can also use ranges (shown later).
28
Accessing Matrix Elements
>> M = [1, 3, 2, 9; 6, 7, 8, 1; 7, 4, 6, 0]
M =
1 3 2 9
6 7 8 1
7 4 6 0

>> M(2, 3)
ans =
8

>> M(3, 1)
ans =
7

>> M(0, 1)
??? Subscript indices must either be real
positive integers or logicals.

>> M(9)
ans =
6
29
Matrix Linear Indexing

30
Indexing: Sub-matrix
• v(2:5) represents the second through fifth elements
– i.e., v(2), v(3), v(4), v(5).
• v(2:end) represents the second till last element of v.
• v(:) represents all the row or column elements of vector v.

• A(:,3) denotes all elements in the third column of matrix A.


• A(:,2:5) denotes all elements in the second through fifth
columns of A.
• A(2:3,1:3) denotes all elements in the second and third
rows that are also in the first through third columns.
• A(end,:) all elements of the last row in A.
• A(:,end) all elements of the last column in A.
• v = A(:) creates a vector v consisting of all the columns of A
stacked from first to last.

31
Exercise
>> v = 10:10:70
v =
10 20 30 40 50 60 70

>> v(2:5)
ans =
20 30 40 50

>> v(2:end)
ans =
20 30 40 50 60 70

>> v(:)
ans =
10
20
30
40
50
60
70

32
>> A(end,:)
ans =
23 83 13 0 10

Exercise >> A(:,end)


ans =
2
25
>> A = [4 10 1 6 2; 8 1.2 9 4 25; 7.2 5 7 1 11
11; 0 0.5 4 5 56; 23 83 13 0 10] 56
10
A =
4.0000 10.0000 1.0000 6.0000 2.0000 >> v = A(:)
8.0000 1.2000 9.0000 4.0000 25.0000 v =
7.2000 5.0000 7.0000 1.0000 11.0000 4.0000
0 0.5000 4.0000 5.0000 56.0000 8.0000
23.0000 83.0000 13.0000 0 0.0000 7.2000
0
>> A(:,3) 23.0000
ans = 10.0000
1 1.2000
9 5.0000
7 0.5000
4 83.0000
13 1.0000
9.0000
>> A(:,2:5) 7.0000
ans = 4.0000
10.0000 1.0000 6.0000 2.0000 13.0000
1.2000 9.0000 4.0000 25.0000 6.0000
5.0000 7.0000 1.0000 11.0000 4.0000
0.5000 4.0000 5.0000 56.0000 1.0000
83.0000 13.0000 0 10.0000
5.0000
0
>> A(2:3,1:3)
2.0000
ans =
25.0000
11.0000
8.0000 1.2000 9.0000
7.2000 5.0000 7.0000
56.0000
10.0000
33
Linear indexing: Advanced
>> A = 5:5:50
A =
5 10 15 20 25 30 35 40 45 50

>> A([1 3 6 10])


ans =
5 15 30 50

>> A([1 2 3 6 10])


ans =
5 10 15 30 50

>> A([1 3 6; 7 9 10])


ans =
5 15 30
35 45 50

34
Linear indexing is useful: find
>> A = [1 2 3; 4 5 6; 7 8 9]
A =
1 2 3
4 5 6
7 8 9

>> B = find(A > 5) % returns linear index


B =
3
6
8
9

>> A(B) % same as A( find(A > 5) )


ans =
7
8
6
9
35
Advanced: Logical indexing
>> A = [1 2 3; 4 5 6; 7 8 9]
A =
1 2 3
4 5 6
7 8 9

>> B = logical([0 1 0; 1 0 1; 0 0 1])


B =
0 1 0
1 0 1
0 0 1

>> A(B)
ans =
4
2
6
9

36
Logical indexing is also useful!
>> A = [1 2 3; 4 5 6; 7 8 9]
A =
1 2 3
4 5 6
7 8 9

>> B = (A > 5) % true or false


B =
0 0 0
0 0 1
1 1 1

>> A(B) % same as A( A > 5 )


ans =
7
8
6
9
37
Subscripting Examples

38
More dimensions possible
>> rand(4,4,3)

ans(:,:,1) =

0.7431 0.7060 0.0971 0.9502


0.3922 0.0318 0.8235 0.0344
0.6555 0.2769 0.6948 0.4387
0.1712 0.0462 0.3171 0.3816

ans(:,:,2) =

0.7655 0.4456 0.2760 0.1190


0.7952 0.6463 0.6797 0.4984
0.1869 0.7094 0.6551 0.9597
• The first index references array 0.4898 0.7547 0.1626 0.3404
dimension 1, the row.
• The second index references ans(:,:,3) =
dimension 2, the column. 0.5853 0.5060 0.5472 0.8407
0.2238 0.6991 0.1386 0.2543
• The third index references 0.7513 0.8909 0.1493 0.8143
dimension 3, the page. 0.2551 0.9593 0.2575 0.2435

39
Extending Matrices
• You can add extra elements to a matrix by creating them
directly using ()
• Or by concatenating (appending) them using [ , ] or
[ ; ]
• If you don’t assign array elements, MATLAB gives them
a default value of 0
>> h = [12 11 14 19 18 17]
h =
12 11 14 19 18 17

>> h = [h 13]
h =
12 11 14 19 18 17 13

>> h(10) = 1
h =
12 11 14 19 18 17 13 0 0 1

40
Example
>> a = [2 4 20]
a =
2 4 20

>> b = [9, -3, 6]


b =
9 -3 6

>> [a b]
ans =
2 4 20 9 -3 6

>> [a, b]
ans =
2 4 20 9 -3 6

>> [a; b]
ans =
2 4 20
9 -3 6
41
Functions on Arrays
• Standard MATLAB functions (sin, cos, exp, log, etc) can
apply to vectors and matrices as well as scalars.
• They operate on array arguments to produce an array
result the same size as the array argument x.
• These functions are said to be vectorized functions.
• In this example y is [sin(1), sin(2), sin(3)]
• So, when writing functions (later lectures) remember
input might be a vector or matrix.
>> x = [1, 2, 3]
x =
1 2 3

>> y = sin(x)
y =
0.8415 0.9093 0.1411
42
Exercise
>> x = linspace(0, 2*pi, 9) % OR x = linspace(0, 2*pi, 31)
x =
0 0.7854 1.5708 2.3562 3.1416 3.9270 4.7124 5.4978 6.2832

>> y = sin(x)
y =
0 0.7071 1.0000 0.7071 0.0000 -0.7071 -1.0000 -0.7071 -0.0000

>> plot(x,y)

43
Matrix vs. Array Arithmetic
• Multiplying and dividing vectors and
matrices is different than multiplying and
dividing scalars (or arrays of scalars).
• This is why MATLAB has two types of
arithmetic operators:
– Array operators: where the arrays operated on
have the same size. The operation is done
element-by-element (for all elements).
– Matrix operators: dedicated for matrices and
vectors. Operations are done using the matrix as
a whole.
44
Matrix vs. Array Operators

Symbol Operation Symbol Operation


+ Matrix addition + Array addition
- Matrix subtraction - Array subtraction
* Matrix multiplication .* Array multiplication
/ Matrix division ./ Array division
\ Left matrix division .\ Left array division
^ Matrix power .^ Array power
* idivide() allows integer division with rounding options

45
Matrix/Array Addition/Subtraction
• Matrices and arrays are
treated the same when
adding and subtracting.
• The two matrices should
have identical size.
• Their sum or difference
has the same size, and is
obtained by adding or
subtracting the
corresponding elements.
• Addition and subtraction
are associative and
commutative.

46
More …
• A scalar value at either side of the operator is
expanded to an array of the same size as the
other side of the operator.

47
Array Multiplication
• Element-by-element
multiplication.
• Only for arrays that
are the same size.
• Use the .* operator
not the * operator.
• Not the same as
matrix multiplication.
• Useful in
programming, but
students make the
mistake of using *

48
Using Array Multiplication (Plot)

• Plot the >> t = 0:0.003:0.5;


>> y = exp(-8*t).*sin(9.7*t+pi/2);
following >> plot(t,y)
function: 1.2

• Notice the use 1

of .* operator 0.8

0.6

0.4

0.2

-0.2
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5

49
Matrix Multiplication
• If A is an n × m
matrix and B is a
m × p matrix, their
matrix product AB
is an n × p matrix, in
which the m entries
across the rows of A
are multiplied with
the m entries down
the columns of B.
• In general, AB ≠ BA
for matrices. Be
extra careful.
50
Matrix Multiplication

>> A = [6,-2;10,3;4,7];
>> B = [9,8;-5,12];
>> A*B
ans =
64 24
75 116
1 116

51
Array Division
• Element-by-element
division.
• Only for arrays that
are the same size.
• Use the ./ operator
not the / operator.
• Not the same as
matrix division.
• Useful in
programming, but
students make the
mistake of using /

52
Matrix Division
‫ۯ‬
• An n × n square = ‫ ۯ‬۰ −1
۰
matrix B is called
invertible (also ۰ ۰−1 = ۷
nonsingular) if
there exists an
n × n matrix B-1
such that their
multiplication is
the identity matrix.

53
Matrix Division
>> A = [1 2 3; 3 2 1; 2 1 3];
>> B = [4 5 6; 6 5 4; 4 6 5];
>> A/B
ans =
0.7000 -0.3000 0
-0.3000 0.7000 0.0000
1.2000 0.2000 -1.0000

>> format rat


>> A/B
ans =
7/10 -3/10 0
-3/10 7/10 *
6/5 1/5 -1

54
Matrix Left Division
• Use the left division
operator (\) (back slash)
to solve sets of linear
algebraic equations.
• If A is n × n matrix and B
is a column vector with n
elements, then x = A\B is
the solution to the
equation Ax = B.
• A warning message is
displayed if A is badly
scaled or nearly singular.

55
Homework: Mesh Analysis
KVL @ mesh 2:
1(i2 − i1) + 2i2 + 3(i2 − i3) = 0
KVL @ supermesh 1/3:
−7 +1(i1 − i2) + 3(i3 − i2) + 1i3 = 0
@ current source:
7 = i1 − i3
Three equations:
−i1 + 6i2 − 3i3 = 0
i1 − 4i2 + 4i3 = 7
i1 − i3 = 7
Solution:
i1 = 9A, i2 = 2.5A, i3 = 2A

56
Just between us…
• Matrix division and matrix left division
are related in MATLAB by the equation:

B/A = (A'\B')' % reversing

• To see the details, type: doc mldivide


or type: doc mrdivide

57
Array Left Division
• The array left division
A.\B (back slash)
>> A = [-4 5; 3 2];
divides each entry of B >> B = [24 20; -9 4];
by the corresponding
entry of A. >> A.\B % notice the back slash
ans =
• Just like B./A -6 4
-3 2
• A and B must be arrays
of the same size. >> B./A
ans =
• A scalar value for either -6 4
A or B is expanded to -3 2

an array of the same


size as the other.

58
Array Power

59
Matrix Power
• A^k computes matrix
power (exponent).
>> A = [1 2; 3 4];
• In other words, it >> A^3
multiplies matrix A by ans =
37 54
itself k times. 81 118
• The exponent k requires
>> A*A*A
a positive, real-valued ans =
integer value. 37 54
81 118
• Remember: this is
repeated matrix
multiplication
60
Matrix Manipulation Functions
• diag: Diagonal matrices and diagonal of a
matrix.
• det: Matrix determinant
• inv: Matrix inverse
• cond: Matrix condition number (for inverse)
• fliplr: Flip matrices left-right
• flipud: Flip matrices up and down
• repmat: Replicate and tile a matrix

61
Matrix Manipulation Functions
• rot90: rotate matrix 90º
• tril: Lower triangular part of a matrix
• triu: Upper triangular part of a matrix
• cross: Vector cross product
• dot: Vector dot product
• eig: Evaluate eigenvalues and
eigenvectors
• rank: Rank of matrix

62
Exercise
>> A = [1 2 3; 4 5 6; 7 8 9] >> fliplr(A)
A = ans =
1 2 3 3 2 1
4 5 6 6 5 4
7 8 9 9 8 7

>> diag(A) >> flipud(A)


ans = ans =
1 7 8 9
5 4 5 6
9 1 2 3

>> det(A) >> rot90(A)


ans = ans =
6.6613e-016 3 6 9
2 5 8
1 4 7

63
Exercise
>> A = [1 2 3; 4 5 6; 7 8 9] >> [V, D] = eig(A)
A =
1 2 3 V =
4 5 6 -0.2320 -0.7858 0.4082
7 8 9 -0.5253 -0.0868 -0.8165
-0.8187 0.6123 0.4082
>> tril(A)
ans =
1 0 0 D =
4 5 0 16.1168 0 0
7 8 9 0 -1.1168 0
0 0 -0.0000
>> triu(A)
ans =
1 2 3
0 5 6
0 0 9

64
Exercise
• Define matrix A of dimension 2 by 4 whose (i,j) entries
are A(i,j) = i+j
• Extract two 2 by 2 matrices A1 and A2 out of matrix A.
– A1 contains the first two columns of A
– A2 contains the last two columns of A
• Compute matrix B to be the sum of A1 and A2
• Compute the eigenvalues and eigenvectors of B
• Solve the linear system B x = b, where b has all entries = 2
• Compute the determinant of B, inverse of B, and the
condition number of B
• NOTE: Use only MATLAB native functions for all above.
65
Solution
>> A =[0 1 2 3; 1 2 3 4] >> b = [2; 2]
A = b =
0 1 2 3 2
1 2 3 4 2

>> A1 = A(:,1:2) >> B\b


A1 = ans =
0 1 -1.0000
1 2 1.0000

>> A2 = A(:,3:4) >> det(B)


A2 = ans =
2 3 -4
3 4
>> inv(B)
>> B = A1 + A2 ans =
B = -1.5000 1.0000
2 4 1.0000 -0.5000
4 6
>> cond(B)
ans =
17.9443
66
67

You might also like