T2 Vector and Matrix

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

'

TOPIC 2

Vectors and Matrices


Creation
Reference
Modification
Functions

Scalar, Vector and Matrix


• Matlab is written to work with matrices.
• Matrices are used to store sets of values
• A matrix can be visualised as a table of values.
arrays
3 7 5 1 3
7 3 6
2 4 9 3 2 9
8 0 4 6 row vector 5 scalar
3 x 4 matrix Column vector

• Vectors and scalars are subset of matrices.


• A scalar has dimension 1 x 1.
• A row vector have dimension of 1 x n, and a column
vector n x 1.
• Vector and matrix are collectively known as array. 2

1
'

Vectors
Creating Row & Column vectors
Referring to elements
Changing, Extending & Deleting elements

Creating Row Vector


Several ways;
a) Put the values of the vector in square brackets
separate by space or coma.

>> load=[3 7 5 4]
load =
3 7 5 4

>> dist=[1,3,4,6]
dist =
1 3 4 6

2
'

Creating Row Vector ‐ cont’d


b) Use colon operator for vector with constant spacing
by specifying the first term, the spacing, and the last
term.
>> load=[1:3:10]
With [ ]
load =
1 4 7 10

>> load=1:3:15
Without [ ]
load =
1 4 7 10 13

>> dist=3:7 Default step 1


dist =
3 4 5 6 7 5

Creating Row Vector ‐ cont’d


c) Use linspace function for vector with constant
spacing by specifying the first term, the last term,
and the number of terms.
>> dist=linspace(0,14,4)
dist =
0 4.6667 9.3333 14.0000

Vector variables can also be created by concatenating


existing vectors.
>> a1 = [4 3 6]; a2 = [2 1 5];

>> vec = [a2 a1] concatenate


vec =
2 1 5 4 3 6 >>vec1=[10 a1]?
6

3
'

Creating Column Vector


To create column vector;
a) Put the values of the vector in square brackets
separate by semicolon ( ; ) or pressing Enter key
after each element typed.

semicolon Enter key


>> d=[3;1;5;4] >> e=[3
d = 5
3 6]
1 e =
5 3
4 5
6
7

Creating Column Vector ‐ cont’d


b) By transposing row vector
>> v=[1:2:5]'
Use apostrophe ( ‘ )
v = to transpose vector
1
3
5

>> rowv=3:4:11;
>> colv=rowv'
colv =
3
7
11 No direct way using colon
operator to get column vector
8

4
'

Referring to Vector Elements


A particular element can be accessed by using the name
and the element number (index/subscript) in brackets.
>>vec=[2 1 5 9 3 4];
Single element
>> vec(3)
ans =
5 What about column vector?
cvec=[1:3:16]’]
>> a=vec(3:5) >> colv(2)?
Range of
a = elements
>> colv(2:4)?
5 9 3 >> colv([3 5 6])?

>> b=vec([2 4 6]) Specific


b = elements
1 9 4
9

Changing, Extending & Deleting Elements

Value stored in vector element can be changed by


specifying the index
>> a1 = [4 3 6];

>> a1(2)=7 Element 2


changed to 7
a1 =
4 7 6

Vector can also be extended


Index specified
>> a1(5)=2 beyond existing size;
a1 = note that 0 is padded

4 7 6 0 2
10

5
'

Changing, Extending & Deleting Elements ‐ cont’d

An element, or range of elements from the existing vectors


can be deleted.
>> st=2:9
st =
2 3 4 5 6 7 8 9

>> st(4)=[]
st =
2 3 4 6 7 8 9

>> st(2:3)=[] vector


st = becomes
shorter
2 6 7 8 9
11

Practice Problem
Do not type the vectors explicitly

1. Use colon operator (:) or linspace;


a) create vector v = 1 2 3 4 5 6 5 4 3 2.
b) extract the last 3 elements of v and assign to v1 , then use
v1 to create v2.
v1 = 4 3 2 v2 = 4 3 2 4 3 2
c) Create a column vector cv which is made up of the last 4
elements of v .
d) What is the value of w, if w=cv(3).
e) Modify v by removing the fifth element until the end of
the vector.
2. Create a 10 elements row vector where each element is 2.
12

6
'

Matrices
Creating
Modifying
Special Matrices

13

Creating Matrix Variables


It is just a generalisation of creating row and column vector.
• Values within row are separated by either space or coma.
• Different rows are separated by semicolon or pressing Enter key.

semicolon Enter key


>> k1=[5 4 8;3 9 1] >> k2=[1 5 3
k1 = 6 4 8]
5 4 8 k2 =
3 9 1 1 5 3
6 4 8

All rows must have the same number of elements


14

7
'

Creating Matrix Variables ‐ cont’d


Rows of matrix can also be entered using colon
operator and linspace function.

>> sv=[4 0 2 7;9:-2:3;linspace(1,15,4)]


sv =
4.0000 0 2.0000 7.0000
9.0000 7.0000 5.0000 3.0000
1.0000 5.6667 10.3333 15.0000

15

Special Matrices
zeros >> z0=zeros(2,3)
z0 = >>zeros(3)?
0 0 0
0 0 0

ones >> wan=ones(2,4)


wan =
1 1 1 1 >>ones(3)?
1 1 1 1

eye >> idn=eye(3)


idn = >>eye(2,3)?
1 0 0
0 1 0
0 0 1 16

8
'

Practice Problem

With the aid of special matrices, create the following.


a) 4 x 5 matrix in which the first two rows are 0s and the next
two rows are 1s.
b) 6 x 6 matrix in which the middle two rows and the middle
two columns are 1s, and the rest are 0s.
c) 2 x 3 matrix where all the elements is 10.
d) 3 x 3 matrix where all are zeros except the leading
diagonal 10.

17

Referring to Matrix Elements


>> k=[2:6;3:2:11] Create matrix k
k =
2 3 4 5 6
3 5 7 9 11

To refer to matrix elements, the row and column are


typed in the brackets.
>> k(2,4)
Extracting single element:
ans = Row 2, col 4
9

>> k1=k(1:2,2:3)
k1 = Extracting a subset of a matrix:
3 4 Row 1‐2, col 2‐3
5 7 18

9
'

Referring to Matrix Elements ‐ cont’d


Matrix k
2 3 4 5 6
3 5 7 9 11

• Using colon (:) for row index means all row


• Using colon for column index means all column
>> r2=k(2,:) Extracting entire row 2
r2 =
3 5 7 9 11

>> k(:,5)
ans = Extracting entire column 5
6 k2=k(2,3:end)?
11
k3=k(end,3)?19

Modifying Variables

• Once a variable exists ( scalar, vector, or matrix)


‐ it can be changed to any other size, or type, of
variable.
• For example, a scalar can be changed to a vector or a
matrix; a vector can be changed to a scalar, a vector of
different length, or a matrix; and a matrix can be
changed to have a different size, or be reduced to a
vector or a scalar.
• These changes are made by adding or deleting
elements.

20

10
'

Modifying Matrix Elements


• Individual element in a matrix can be modified by
assigning value.
>> mat=[2:5;4:7];
>> mat(2,3)=10
Modify single element
mat =
2 3 4 5
4 5 10 7

>> mat(1,:)=6:9 Modify entire row - must


mat = assign vector with the
6 7 8 9 correct length
4 5 10 7

Modify entire column ?


21

Modifying Matrix Elements ‐ cont’d


>> m=[3 4 8 >> m(:,3)=[9 8]’
6 10 7]; m =
3 4 9
6 10 8

>> m(:,3)=[5 4] Without


transposing
m =
3 4 5
6 10 4

>> m(:,3)=2 One value


m =
3 4 2
6 10 2 22

11
'

Extending Matrix

The size of added row/column must fit the existing matrix

>> vec=[2:4;6:8];
>> vec(:,4)=[1,5]'
vec = Fourth column added
2 3 4 1
6 7 8 5

>> vec(3,:)=[2:2:8]
vec =
2 3 4 1 Third row added
6 7 8 5
2 4 6 8
>> vec(:,5)=[1 5 7] ?
23

Extending Matrix ‐ cont’d


>> vec(:,6)=[6 7 1]’ Column padded with 0’s
vec =
2 3 4 1 0 6
6 7 8 5 0 7
2 4 6 8 0 1

>> vec(4,3)=9
vec =
2 3 4 1 0 6
6 7 8 5 0 7
2 4 6 8 0 1
0 0 9 0 0 0
>>vec(6,7)=8 ?
Matrices can also be concatenated like vectors
provided the row/column fit each other. 24

12
'

Deleting Matrix Elements

Individual elements cannot be deleted from a matrix, but


entire row/column can be deleted.

>> mat=[4 9 3 7 8;8 4 2 6 9;3 1 7 4 3]


mat =
4 9 3 7 8
8 4 2 6 9
3 1 7 4 3

>> mat(:,2:4)=[]
All rows column 2
mat =
through 4 deleted
4 8
8 9
3 3
Delete second row ? 25

Practice Problem
Create vector v = 7 5 3 1. Use v to create the following
matrices;
a) m1 = 7 5 3 1 7 5 3 1
b) m2 = 7 5 3 1
7 5 3 1

c) m3 = 7 7
5 5
3 3
1 1

Delete columns 2 and 3 of m2.


Delete the first row of m3.
26

13
'

Array Functions
Functions used for manipulating arrays

27

Matrix Using rand Function

Square

>> rand(2)
ans =
0.1576 0.9572
0.9706 0.4854

rectangular

>> rand(3,2)
ans =
0.6557 0.9340
0.0357 0.6787
0.8491 0.7577
28

14
'

Matrix Using randi Function

Scalar 1‐2 Range 1‐3 Size 2 x 2

>> randi(2) >> randi(3,2)


ans = ans =
1 1 1
3 2

Range 1‐5 Size 2 x 3 Size 2 x 3


Range 6‐9

>> randi(5,2,3) >> randi([6,9],2,3)


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

Built‐in Functions For Array


Function Description Example
mean(A) Mean value of elements >> A=[5 3 8 6];
of the vector >> mean(A)
ans =
5.5000
max(A) The largest element of the >> max(A)
vector ans =
min(A) 8
for
smallest [m,n]=max(A) m is the largest element in >> [m,n]=max(A)
vector, and n is the m =
position of the element 8
n =
3
sum(A) Sum of the elements of >> sum(A)
the vector ans =
22
sort(A) Arranges the elements in >> sort(A)
ascending order ans =
3 5 6 8 30

15
'

Built‐in Functions For Array


Function Description Example
median(A) Median value of >> median(A)
elements of the vector ans =
5.5000
std(A) Standard deviation of >> std(A)
the element of the ans =
vector 2.0817
cumsum(A) / Stores cumulative >> cumsum(a)
cumprod (A) sum/product for each ans =
step as it adds the 5 8 16 22
elements from the
vector >> cumprod(a)
ans =
5 15 120 720

If A is matrix the above functions, row vector will be


returned which do the calculations column wise

31

Built‐in Functions For Array


Function Description Example
dot(A,B) Calculates the dot (scalar) >> A=[3 2 5];B=[4 6 1];
product of vectors A and B. >> dot(A,B)
The vectors can each be row or ans =
column vectors. 29
cross(A,B) Calculates the cross product of >> cross(A,B)
vectors A and B. The vectors ans =
must have 3 elements. -28 17 10

det(A) & inv(A) functions return the determinant


and inverse matrix of square matrices, respectively

32

16
'

Example

>> mt= [2 5 7 4;6 9 3 5;8 7 3 1]


>> mean(mt)
ans =
5.3333 7.0000 4.3333 3.3333
mean(mean(mt))=?

>> cumsum(mt)
ans =
2 5 7 4
8 14 10 9
16 21 13 10
33

Try This !

How to get the overall maximum of a matrix.

>> mt= [2 5 7 4;6 9 3 5;8 7 3 1]


>> max(max(mt))
ans= ?

34

17
'

Array Functions
Functions used for managing & handling arrays

35

Array Functions ‐ Matrix Dimension


Vector v Matrix m
4 6 5 8 3 9 8
2 5 3

Some built‐in functions for managing and handling array


Function Description Example

length Returns number of; >> length(v) >> length(m)


i) elements in vector. ans = ans =
ii) either row/ column, which 4 3
ever is larger in matrix

size Returns a row vector m n, >> size(v) >> size(m)


where m and n are the number ans = ans =
of rows and columns 1 4 2 3

numel Returns the total number of >> numel(v) >> numel(m)


elements in any array ans = ans =
4 6
36

18
'

Array Functions ‐ Matrix Dimension


Matrix m 3 9 8
Vector v 4 6 5 8
2 5 3

Function Description Example

end Returns to the; >> z=v(end) >> mz=m(end,2)


Note: used i) last element in a vector. z = mz =
only as ii) last row if end is in the row 8 5
index index, vice versa for column.

reshape Change the dimension of a >> reshape(m,3,2)


matrix. It iterates through the ans =
matrix counterclockwise. 3 5
2 8
9 3
[? ?] Note; vector of variables on the >> [r c]=size(m)
LHS of assignment. The first r=
value returned is number of 2
rows and the second is columns. c =
3
37

Array Functions ‐ Matrix Dimension


Matrix m 3 9 8
Vector v 4 6 5 8
2 5 3

Function Description Example

fliplr Flips array left‐right. >> a=fliplr(v) >> fliplr(m)


a = ans =
8 5 6 4 8 9 3
3 5 2

flipud Flips matrix up‐down >> flipud(m)


ans =
2 5 3
3 9 8
rot90 rotates array 90o >> rot90(v) >> rot90(m)
counterclockwise ans = ans =
8 8 3
5 9 5
6 3 2
4
38

19
'

Array Functions ‐ Matrix Dimension


Matrix m 3 9 8
Vector v 4 6 5 8
2 5 3
4 6 1

Function Description Example

diag ( v) When v is a >> diag(v)


vector, creates a ans =
square matrix with 4 0 0 0
the elements of v 0 6 0 0
in the diagonal. 0 0 5 0
0 0 0 8
diag(m) When m is a >> diag(m)
matrix, creates a ans =
vector from the 3
diagonal of m. 5
1

More array manipulation function can be found in the Help Window


Select Function by Category / mathematics / arrays and matrices 39

Try This !
What would be produced by the following sequence of statements
and expressions.
– mt=[7:-2:3;23 6 9;3:5]
– mt(2,3)
– mt(1,:)
– mt(:,4)=[7 3 2]‘
– size(mt)
– length(mt)
– numel(mt)
– vc=mt(2,:)
– vc(vc(4))
– vc(1:2)=[]
– reshape(mt,4,3)
– zeros(size(mt))
40

20
'

Strings as Variables

41

Strings as Variables
• String is a train of characters created by typing
characters within single quotes (‘).
• Can include letters, digits, other characters and
spaces.
• String are used in output commands, formatting
commands of plot, input argument of some
functions.
• When a variable is defined as a string, the characters
are stored in array just as number are, including
spaces.

42

21
'

vector
Strings as Variables
>> k='SKAM 1422' Create string >> a=352
variable
k = a =
SKAM 1422 352 Numbers are
right justify
>> k(4)
>>s=k(5)? >> b='352'
ans =
>>length(s)? b =
M Strings are
352 left justify
>> k(4)=‘A’
Modifying a≠ b
k = a is a number
string variable
SKAA 1422 b is a string

>> k(6:9)=‘3413' Modifying


k = string variable
SKAA 3413
43

matrix
Strings as Variables
• String can also be placed in matrix; using semicolon or enter
key, but all rows must have the same length, which may
cause problem when creating rows of specific wording.
• Matlab has char function that creates rows with the same
number of characters by automatically adding spaces to the
shorter rows.
• Coma is used to separate the rows.

>> student=char('Name: Mohd Ali','Grade: A+')


student =
Name: Mohd Ali
Grade: A+
>> size(student)
ans =
2 14 44

22
'

Practice Problem
1. Write the shortest Matlab statement for the following problems.
a) sum of even numbers from 2 to 100
b) Create the following matrix by typing one command. Do not type
individual elements explicitly.

1 2 3 4 1 0 7 0 0 0 0
k = 1 1 1 1 h = 2 0 6 m = 0 0 7 7
5 5 5 5 3 0 5 0 0 7 7

Practice Problem
2. Create three row vectors:
a = [3 6 ‐4 7 2] b = [6 ‐8 5 9 3] c = [5 ‐2 7 0 8]
Use the three vectors to create the following matrices.
(a) the first, second, and third rows consist of the first three elements
of the vectors a, b, and c, respectively.
(b) the first, second, and third columns consist of the last three
elements of the vectors a, b, and c, respectively.

3. Using the zeros, ones, and eye commands create the following arrays

1 0 0 1 1 0 0 1 1
0 1 0 1 1 0 0 1 1
0 0 0 0
1 1 1 1

23
'

Practice Problem
4. Create matrix A. 1 2 3 4 5 6
A= 7 8 9 10 11 12
13 14 15 16 17 18

Use matrix A to create:


(a) a six‐element row vector ha that contains the elements of the first row
of A.
(b) a three‐element row vector named hb that contains the elements of
the sixth column of A.
(c) a six‐element row vector named hc that contains the first three
elements of the second row of A and the last three element of the
third row of A

Practice Problem
5. Create matrix k.
4 8
k= 16 2

4 8 ‐4 ‐8
a) Use k to create a 4x4 matrix m. 16 2 ‐16 ‐2
m= ‐4 ‐8 4 8
‐16 ‐2 16 2

4 1 ‐4 ‐8
b) Modify matrix m be as shown. 1 1 1 1
m= ‐4 1 4 8
‐16 1 16 2

24
'

Thank You

50

25

You might also like