Vectors Matrices

You might also like

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

TOPIC 2

Vectors and Matrices


Creation
Reference
Modification
Functions

1
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
Vectors
Row & Column vectors
Creating
Modifying

3
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

4
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]
load =
With [ ]
1 4 7 10

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

>> dist=3:7
dist = Default step 1
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] >>vec1=[10 a1]?


vec =
2 1 5 4 3 6 >>vec2=[a1;a2]
6 ?
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 4 3 6];

>> vec(3)
ans = Single element
5

>> vec3=vec(3:5) Range of


vec3 = elements
5 4 3

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


vec4 = elements
1 4 6 7
Changing Vector element & Extending Vector
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


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

8
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.

Enter key
semicolon >> disp=[3
>> disp=[3;1;5;4] 5
disp = 6]
3 disp =
1 3
5 5
4 6

9
Creating Column Vector – cont’d
b) By transposing row vector

Use apostrophe ‘ to transpose vector

>> v=[1:2:5]' >> rowv=3:4:11;


v = >> colv=rowv'
1 colv =
3 3
5 7
11

No direct way using colon operator to get column vector

10
Matrices
Creating
Modifying
Special Matrices

11
Creating Matrix Variables
It is just a generalisation of creating row and column
vector variables;
• Values within row are separated by either space
or coma.
• Different rows are separated by semicolon or
pressing Enter key.
semicolon Enter key
>> K=[5 4 8;3 9 1] >> k2=[1 5 3
K = 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 12


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

13
Try This !
Think what would be produced by the following sequence of
statements and expressions. (Parts (b), (c), and (d) use the vector
that was defined in part (a).)
(a) m=9:-2:1 (b) m2=[m m] (c) n=[m;m] (d) p=[m’ m’]

>> m=9:-2:1
m = >> p=[m' m']
9 7 5 3 1 p =
>> m2=[m m] 9 9
m2 = 7 7
9 7 5 3 1 9 7 5 3 1 5 5
>> n=[m;m] 3 3
n = 1 1
9 7 5 3 1
9 7 5 3 1
14
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
15
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
16
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 17
Try This !

Use ones /zeros functions to create the following arrays:


a) vector 10 10 10 10 10

b) matrix 10 10 10
10 10 10

18
Referring to Matrix Elements
To refer to matrix elements, the row and column are
typed in the brackets.
>> k=[2:6;3:2:11]
k =
Create matrix k
2 3 4 5 6
3 5 7 9 11

>> k(2,4)
Extracting single element:
ans = Row 2, col 4
9

>> k1=k(1:2,2:3) Extracting a subset of a matrix:


k1 = Row 1-2, col 2-3
3 4
5 7 19
Referring to Matrix Elements – cont’d
Matrix k
2 3 4 5 6
3 5 7 9 11

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


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

>> k(:,5) Extracting entire column 5


ans =
6 k2=k(2,3:end)?
11 20
k3=k(end,3)?
Modifying Variables

• Once a variable exists—as a 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.

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

>> mat(1,:)=6:9
mat = Modify entire row - must
assign vector with the
6 7 8 9 correct length
4 5 10 7

Modify entire column ?


22
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 23
Try This !
1. Use ones /zeros functions, create a 4 x 5 matrix in which the first two
rows are 0s and the next two rows are 1s.

2. Create a 6 x 6 matrix in which the middle two rows and the middle two
columns are 1s, and the rest are 0s.

24
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] ?
25
Extending Matrix - cont’d
>> vec(:,6)=[6 7 1]’
vec =
2 3 4 1 0 6 Column padded
with 0’s
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. 26
Deleting Elements
An element, or range of elements from the existing
variables can be deleted.

Vector
>> st=2:9
st =
2 3 4 5 6 7 8 9

>> st(4)=[]
st =
2 3 4 6 7 8 9 vector
becomes
shorter
>> st(2:3)=[]
st =
2 6 7 8 9
27
Deleting Elements - cont’d
Matrix
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 ? 28
Try This !
What would be produced by the following sequence of statements and
expressions.
a) A=[N(1,1:4)’,N(2,2:5)’]
b) B=[N(:,3)' N(3,:)]
c) C(3:4,5:6)=N(2:3,4:5)

29
Array Functions
Functions used for manipulating arrays

30
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 >> max(A)
the vector ans =
min(A) 8
for
smallest [m,n]=max(A) m is the largest element >> [m,n]=max(A)
in 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 31
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 an array the above functions, row vectors will


be returned which do the calculations column wise
32
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

33
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

>> cumsum(mt)
ans =
2 5 7 4
8 14 10 9
16 21 13 10
34
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= ?

Using the ones and zeros commands, create a 4 x 3 matrix in which the first
two rows are 0s and the next two rows are 1s.
>> a=zeros(2,3);
>> a(3:4,:)=ones(2,3)
a =
0 0 0
0 0 0
1 1 1
1 1 1
35
or >> a=[zeros(2,3);ones(2,3)]
Array Functions
Functions used for managing & handling arrays

36
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
37
Array Functions - Matrix Dimension (cont’d)
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 the through ans =
the 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
38
Array Functions - Matrix Dimension (cont’d)
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
39
Array Functions - Matrix Dimension (cont’d)
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 40
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)) 41
Strings as Variables

42
Strings as Variables
• String is an 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.

43
vector
Strings as Variables - cont’d
>> k='SKAM 1422' Create string
k = variable >> a=352
SKAM 1422 a =
Numbers are
352 right justify
>> k(4)
ans = >>s=k(5)? >> b='352'
>>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
44
matrix
Strings as Variables - cont’d
• String can also be placed in matrix; using semicolon
or enter key, but all row must have the same length,
which may cause problem when creating rows of
specific wording.
• Matlab has char function that creates rows of 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 45
More practice see Problem A2

Thank You

46

You might also like