0% found this document useful (0 votes)
14 views

3.1 Arrays and Matrices

Uploaded by

Koskei Vic
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)
14 views

3.1 Arrays and Matrices

Uploaded by

Koskei Vic
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/ 33

Chapter 3:

ARRAYS AND MATRICES

Dr. A. Mile

CUK 1
An array is MATLAB's basic data
structure
• Can have any number of dimensions. Most common are
• vector - one dimension (a single row or column)
• matrix - two or more dimensions
• Scalar - matrices with only one row and one column.
• Arrays can have numbers or letters

2
Creating Matrices
• In MATLAB, a vector is created by assigning the elements of
the vector to a variable.
• This can be done in several ways depending on the source of
the information.
• —Enter an explicit list of elements
• —Load matrices from external data files
• —Using built-in functions
• —Using own functions in M-files

A matrix can be created in MATLAB by typing the elements


(numbers) inside square brackets [ ]
3
>> matrix = [1 2 3 ; 4 5 6 ; 7 8 9]
Examples
Optional commas may be used between
• >> A = [2 -3 5; -1 4 5] the elements
A=
2 -3 5 Type the semicolon (or press Enter) to move to
the next row
-1 4 5
>> x = [1 4 7]
x=
147 Note MATLAB displays row vector horizontally
>> x = [1; 4; 7]
x=
1
4 Note MATLAB displays column vector vertically
7
4
>> cd=6; e=3; h=4;

>> Mat=[e cd*h cos(pi/3);h^2 sqrt(h*h/cd) 14]

Mat =
3.0000 24.0000 0.5000
16.0000 1.6330 14.0000

What if number of columns different?


Four columns Five columns
>> B= [ 1:4; linspace(1,4,5) ]
??? Error using ==> vertcat
CAT arguments dimensions are not consistent.
5
Create vector with specified constant
spacing between elements
The colon operator can be used to create a vector with constant
spacing
x = m:q:n
• m is first number
• n is last number
• q is difference between consecutive numbers
>>x=[1:2:10]
x=
1 3 5 7 9
If omit q, spacing is one
y = m:n
>> y=1:5
6
y=
1 2 3 4 5
Examples
>> x = 1:2:13
x = 1 3 5 7 9 11 13

>> >> 0.2:0.5:2.4 Non-integer spacing


ans =
0.2000 0.7000 1.2000 1.7000 2.2000

>> 2:5
ans =
2 3 4 5 No middle step value - default for the step is 1.

>> -2:3
ans =
-2 -1 0 1 2 3 If the last numbers cannot be obtained by
>> -3:3:10 adding steps to first, then the last element in
ans = the vector will be the number that does not
-3 0 3 6 9 exceed last
>> 1.5:-0.5:-0.5 7
ans = negative step is also possible
1.5000 1.0000 0.5000 0 -0.5000
Create vector with specified number of
terms b/w first and last
v = linspace( xi, xf, n )
• xi is first number
• xf is last number
• n is number of terms (= 100 if omitted)
>>f= linspace(0, 10, 5)
f=
0 2.5000 5.0000 7.5000 10.0000 5 elements, from 0 to 10
>>g= linspace(0, 10)
g=
Columns 1 through 10
0 0.1010 0.2020 0.3030 0.4040 ............................................
......................Columns 91 through 100
9.0909 9.1919 9.2929 9.3939 9.4949 9.5960 9.6970 9.7980 8
9.8990 10.0000
>> va = linspace( 0, 8, 6 ) Six elements
va = 0 1.6000 3.2000 4.8000 6.4000 8.0000
>> va = linspace( 30, 10, 11 )
va=30 28 26 24 22 20 18 16 14 12 10
Decreasing elements

m:q:n lets you directly specify


spacing. linspace() lets you
TIP directly specify number of terms
9
Built-in Functions to Generate Matrices
zeros(r,c) - makes matrix of r rows and c
columns, all with zeros
ones(r,c) - makes matrix of r rows and c
columns, all with ones
rand(r,c) - makes matrix of r rows and c
columns, with random numbers
eye(n) - makes square matrix of n rows and
columns. Main diagonal (upper left to lower
right) has ones, all other elements are zero
magic(n) - makes a special square matrix of n 10
rows and c columns, called Durer’s matrix
Examples
>> a=zeros(3,4) >> d=eye(4)

a = 0 0 0 0 d = 1 0 0 0
0 0 0 0
0 1 0 0
0 0 0 0
>> b=ones(4,3) 0 0 1 0
b = 1 1 1 0 0 0 1
1 1 1
>> e=magic(4)
1 1 1
1 1 1 e = 16 2 3 13
>> c = rand(2,3) 5 11 10 8
c =
9 7 6 12
0.8147 0.1270 0.6324 11

0.9058 0.9134 0.0975 4 14 15 1


To make a matrix filled with a particular
number, multiply ones(m,n) by that
TIP
number
>> z=100*ones(3,4)
z =
100 100 100 100
100 100 100 100
100 100 100 100 12
Functions to Handle Matrices and Arrays
• length( ) - number of elements in a array. number of columns
x = [1 2in3];a
matrix y= [1 2 3; 4 5 6];
• >>length(y)
• ans =
• 3
• >>length(x)
• ans =
• 3

• sum( ) – Sum of elements in a array. Sum of elements in a column of
a matrix.
• >>sum(x)
• ans =
• 6
• >>sum(y)
• ans = 13
• 5 7 9
Functions to Handle Matrices and Arrays
‘ – Transpose of a matrix. Convert a row vector to column vector
>>y'
ans = x = [1 2 3];
1 4 y= [1 2 3; 4 5 6];
2 5
3 6
>> x'
ans =
1
2
3

diag( ) – diagonal elements of matrix. crate a matrix with elements of a vector,if the
argument is a vector)
>>diag(y)
ans =
1
5
>>diag(x)
ans =
1 0 0 14
0 2 0
0 0 3
Functions to Handle Matrices and Arrays
• size( ) – size (dimensions) of matrix x = [1 2 3];
>>size(y) y= [1 2 3; 4 5 6];
ans =
2 3 (2 rows, 3 columns)

det( ) – determinant of a matrix. (matrix must be square to get
determinant)
• >> z= [1 2 3; 4 5 6; 7 8 0];
• >> det (z)
• ans =
• 27

• inv( ) – inverse of a square matrix
• >> inv(z)
• ans =
• -1.7778 0.8889 -0.1111
• 1.5556 -0.7778 0.2222 15
• -0.1111 0.2222 -0.1111
Subscripts and Extracting a Sub-Matrix
Can access (read from or write to) elements in
array (vector or matrix) individually or in groups
• Useful for changing subset of elements
• Useful for making new variable from subset of elements

• Address (index) of element is its position in the array


• x(n) – nth element in the vector
• x(i, j)- element in ith row, jth column

16
Examples
>> A=[35 46 78 23 5 14 81 3 55]
A = 35 46 78 23 5 14 81 3 5
>> A(4)
ans = 23
>> A(6)=27
A = 35 46 78 23 5 27 81 3 5
>> A(2)+A(8)
ans = 49
>> A(5)^A(8)+sqrt(A(7))
17
ans = 134
>> MAT=[3 11 6 5; 4 7 10 2; 13 9 0 8]
Column 1

MAT = 3 11 6 5
Element in 4 7 10 2
row 3 and
column 1 13 9 0 8 Row 3
>> MAT(3,1)
ans = 13
>> MAT(3,1)=20 Assign new value to element in row 3 and column 1
MAT = 3 11 6 5
Only this 4 7 10 2
element
changed 20 9 0 8
>> MAT(2,4)-MAT(1,2)
18
ans = -9
Using a Colon : in Addressing Arrays
The colon : lets you address a range • >> A(3,:) % extract the 3rd row
of elements • ans =
• Vector (row or column) 789
• x(:) - all elements • >> A(:,2) % extract the 2nd
• x(m:n) - elements m through n column
• ans =
• Matrix
• A(:,n) - all rows of column n 2
• A(m,:) - all columns of row m 5
• A(:,m:n) - all rows of columns 8
m through n • >> A([1,3],1:2) % extract 1st and
• A(m:n,:) - all columns of rows 2nd elements of 1st and 3rd rows
m through n • ans =
• A(m:n,p:q) - columns p 1 2
through q of rows 7 8 19
m through n
Adding And Deleting Elements
• Indexing can be used to add and delete
elements from a matrix.
A=
• >> A(5,2) = 5 % assign 5 to the position (5,2); 1 2 3
the uninitialized elements become zeros 4 5 8
7 8 9
• >> A(4,:) = [2, 1, 2]; % assign vector [2, 1, 2] to the 0 0 0
4th row of A 0 5 0
• >> A(5,[1,3]) = [4, 4]; % assign: A(5,1) = 4 and
A(5,3) = 4
• A(4,:) = [ ] - will delete 4th row
• A(:, 3) = [ ] – will delete 3rd column A(2:2:6) = [ ]
ans = 1 7 5 3 6 9
• A(1,2) = [ ] – error ……………. How? 20
• Can’t delete single element in a row or column.
More Examples
v = 4 7 10 13 16 19 22 25 28 31 34
>> u=v([3, 5, 7:10])
u = 10 16 22 25 28 31

>> u=v([3 5 7:10])


u = 10 16 22 25 28 31
DF = 1 2 3 4
>> DF(5:7)=10:5:20
DF = 1 2 3 4 10 15 20
>> DF(10)=50
DF = 1 2 3 4 10 15 20 0 0 50

>> A=[10:-1:4; ones(1,7); 2:2:14; zeros(1,7)]


A = 10 9 8 7 6 5 4
1 1 1 1 1 1 1
2 4 6 8 10 12 14
0 0 0 0 0 0 0

>> B=A([1 3],[1 3 5:7]) 21


B = 10 8 6 5 4
2 6 10 12 14
Appending vectors and matrices
• Can only append row vectors to row vectors and column vectors
to column vectors
• If r1 and r2 are any row vectors,
r3 = [r1 r2] is a row vector whose left part is r1 and right part
is r2
• If c1 and c2 are any column vectors,
c3 = [c1; c2] is a column vector whose top part is c1 and
bottom part is c2
• If appending one matrix to right side of other matrix, both must
have same number of rows
• If appending one matrix to bottom of other matrix, both must
have same number of columns

22
Examples r1 = [1 2 3 4 ]
r2 = [5 6 7 8 ]

r = [r1,r2] c1 = [1; 2; 3; 4 ]
r = c2 = [5; 6; 7; 8 ]
1 2 3 4 5 6 7 8
c = [c1; c2]
A = 1 2 3
>> Z=[A B] 4 5 6
Z = 1 2 3 7 8 B = 7 8
9 10
4 5 6 9 10
C = 1 0 0
>> Z=[A; C] 0 1 0
Z = 1 2 3 0 0 1
4 5 6
1 0 0 c=
1
0 1 0
2
0 0 1 3
>> Z=[A; B] 4
??? Error using ==> vertcat 5
CAT arguments dimensions are not 23
6
consistent. 7
8
Operations on Matrices
• Previously dealt with scalars (single numbers). Will now
work with arrays, which in general have more than one
number

24
Addition and Subtraction
When adding/ subtracting two arrays A and B, MATLAB
adds/subtracts the corresponding elements (element wise
addition/subtraction)
When add/subtract a scalar to an array, MATLAB adds /
subtracts the scalar to every element of the array

25
Matrix Multiplication
There are two ways of multiplying matrices – matrix
multiplication and elementwise multiplication
MATRIX MULTIPLICATION
• MATLAB denotes this with asterisk (*)
• Number of columns in left matrix must be same as number of rows
in right matrix

26
Matrix multiplication on two vectors
• They must both be the >> h = [ 2 4 6 ]
same size h =
2 4 6
• One must be a row vector >> v = [ -1 0 1 ]'
and the other a column v =
vector -1
0
• If the row vector is on the
1
left, the product is a scalar >> h * v
• If the row vector is on the ans =
right, the product is a 4
>> v * h
square matrix whose side is
ans =
the same size as the vectors -2 -4 -6
0 0 0 27
2 4 6
Array Division
Left division, \:
Left division is one of MATLAB's two kinds of array
division
• Used to solve the matrix equation AX=B
• A is a square matrix, X, B are column vectors
• Solution is X = A-1B
In MATLAB, solve by using left division operator (\), i.e.,
>> X = A \ B

When solving set of linear equations, use left division,


not inverse, i.e., use X=A\B not X=inv(A)*B
Left division is
• 2-3 times faster
• Often produces smaller error than inv() 28
• Sometimes inv()can produce erroneous results
Right division, /:
Right division is the other kind of MATLAB's array
division
• Used to solve the matrix equation XC=D
• C is a square matrix, X, D are row vectors
• Solution is X = D·C-1
In MATLAB, solve by using right division operator
(/), i.e.,
>> X = D / C

29
Element-by-Element Operations
• Addition and subtraction of arrays is always elementwise
• Multiplication, division, exponentiation of arrays can be
elementwise
• Both arrays must be same dimension

30
Example
ELEMENTWISE MULTIPLICATION
>> A = [1 2; 3 4];
>> B = [0 1/2; 1 -1/2];
>> C = [1 0]’;
>> D = A .* B
D =
0 1
3 -2
>> A .* C
??? Error using ==> times
Matrix dimensions must agree.

31
Built-in Functions for Analyzing Arrays
• mean(v) – mean (average)
• max(v) – maximum value, optionally with index of maximum
• min(v) – minimum value, optionally with index of minimum
• sum(v) – sum
• sort(v) – elements sorted into ascending order
• median(v) – median
• std(v) – standard deviation
• dot(v,w) – dot (inner product); v, w both vectors of same
size but any dimension
• cross(v,w) – cross product; v, w must both have three
elements but any dimension

32
Multi-dimensional Array
•Arrays can have more than two dimensions
•A= [ 1 2; 3 4]
•You can add the 3rd dimension by
•A(:,:,2) = [ 5 6; 7 8]

33

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy