You are on page 1of 36

EXPERIMENT 4

REALIZATION OF
ARRAYS AND MATRICES
ARRAY
● collection of items stored at contiguous
memory locations
● Storing multiple items of same type together
Import numpy
A= numpy.array([0,1,2,3,4,5])
print (A)
ONE DIMENSIONAL ARRAY
● array()
● arange () - np.arange(start, stop, interval)
● linspace() - evenly spaced points - specify no. of elements - linear
np.linspace(start, stop, no. of elements -N), default N=50
● logspace() - produces evenly spaced points on a logarithmically spaced scale

Eg. logspace(1, 3, 5) - array starts at 101 and ends at 103 with 5 points
ONE DIMENSIONAL ARRAY
● zeros(num, dtype=float or int or complex )
● ones(num, dtype=float or int or complex)
- Generate a 1D complex array and concatenate it with 4.3-4.5j, add 4.3-4.5j to
it.
Array Visualization
Using matplotlib library and pyplot function
plot(), stem etc..
TWO DIMENSIONAL ARRAYS

MATRIX - A rectangular arrangement of data


Horizontal entries – Row (r) and Vertical entries - Columns (c )

Matrix A – represented as A[r X c]


EXAMPLE - IMAGES
TWO DIMENSIONAL ARRAYS
● No built-in type functions for matrices in python
● treat list of a list as a matrix
● Using for loop - try it
TWO DIMENSIONAL ARRAYS
import numpy as np
r = int(input("Enter the number of rows:"))
c = int(input("Enter the number of columns:"))
print("Enter the entries in a single line (separated by space): ")
entries = list(map(int, input().split()))
TWO DIMENSIONAL ARRAYS
● Define a list using list()
● split()- create python list from string which is accepted using input()
● Use map() to convert created list to integer values
# For printing the matrix
matrix = np.array(entries).reshape(r, c)
print(entries)
print(matrix)
MATRIX OPERATIONS
● Scalar multiplications - (numpy.multiply(A, b) or A * b)
● Matrix addition - element wise
A = np.array([[2, 4], [5, -6]])
B = np.array([[9, -3], [3, 6]])
C=A+B
print(C)
MATRIX OPERATIONS
● MATRIX MULTIPLICATION - dot product
import numpy as np
A = np.array([[3, 6, 7], [5, -3, 0]])
B = np.array([[1, 1], [2, 1], [3, -3]])
C = A.dot(B)
print(C)
MATRIX OPERATIONS

● MATRIX TRANSPOSE - A.transpose()


● ACCESS MATRIX ELEMENTS
import numpy as np
A = np.array([2, 4, 6, 8, 10])
print("A[0] =", A[0])
print("A[-1] =",A[-1])
MATRIX OPERATIONS

● ACCESS ELEMENTS OF A TWO-DIMENSIONAL ARRAY – ROW ACCESSING


import numpy as np
A = np.array([[1, 4, 5, 12], [-5, 8, 9, 0], [-6, 7, 11, 19]])
# First element of first row
print("A[0][0] =", A[0][0])
Third element of second row
print("A[1][2] =", A[1][2])
# Last element of last row
print("A[-1][-1] =", A[-1][-1])
A[0] - first row extraction
MATRIX OPERATIONS

● ACCESS ELEMENTS OF A TWO-DIMENSIONAL ARRAY – COLUMN


ACCESSING
print("A[:,0] =",A[:,0]) # First Column
print("A[:,3] =", A[:,3]) # Fourth Column
MATRIX OPERATIONS

● SLICING A MATRIX
import numpy as np
A = np.array([[1, 4, 5, 12],
[-5, 8, 9, 0],
[-6, 7, 11, 19]])
print(A[:2, :3]) # two rows, three columns
● DETERMINANT A MATRIX
np.linalg.det()
MATRIX OPERATIONS

● INVERSE OF A SQUARE MATRIX


● A matrix must be square
● have a nonzero determinant
● non invertable matrix - singular matrix
● Using np.linalg.inv
import numpy as np
m = np.array([[4,2],[2,1]])
print("Original matrix:")
print(m)
MATRIX OPERATIONS
result = np.linalg.det(m)
print("Determinant of the given matrix:")
print(result)
if result==0:
print ("this matrix has no inverse")
else :
result = np.linalg.inv(m)
print("Inverse of the said matrix:")
print(result)
SOLVING A SYSTEM OF LINEAR EQUATIONS
SOLVING A SYSTEM OF LINEAR EQUATIONS
solve a system of three linear equations:
4x + 3y + 2z = 25 -(1)
-2x + 2y + 3z = -10 -(2)
3x -5y + 2z = -4 -(3)
x=5, y=3,z=-2
SOLVING A SYSTEM OF LINEAR EQUATIONS
SOLVING A SYSTEM OF LINEAR EQUATIONS
● Using inverse matrix
import numpy as np
A = np.array([[4, 3, 2], [-2, 2, 3], [3, -5, 2]])
B = np.array([25, -10, -4])
X = np.linalg.inv(A).dot(B)
print(X)

OR
X = np.linalg.solve(A,B)
SOLVING A SYSTEM OF LINEAR EQUATIONS
Solve the following equations
2x+y+2z=0
2x-y+z=10
x+3y-z=5
THE RANK OF A MATRIX

● defined as the number of linearly independent columns present in a matrix.


● The number of linearly independent columns is always equal to the number
of linearly independent rows
● inbuilt function in numpy.linalg package
● numpy.linalg.matrix_rank()
import numpy as np
A = np.array([[4, 3, 2], [-2, 2, 3], [3, -5, 2]])
rank = np.linalg.matrix_rank(A)
print('Matrix : ', A)
print('Rank of the given Matrix : ',rank)
EIGEN VALUE AND EIGEN VECTORS

● Eigendecomposition of a matrix- a type of decomposition - involves


decomposing a square matrix into a set of eigenvectors and eigenvalues.
● In Linear Algebra, a scalar λ is called an Eigen value of matrix A if there
exists a column vector v such that
Av=λv
● A matrix- could have one eigenvector and eigenvalue for each dimension of
the parent matrix.
● Not all square matrices can be decomposed into eigenvectors and
eigenvectors, and some can only be decomposed in a way that requires
complex numbers.
EIGEN VALUE AND EIGEN VECTORS

● The parent matrix can be shown to be a product of the eigenvectors and


eigenvalues.
A = Qdiag(V)Q-1
Q - a matrix comprised of the eigenvectors,
diag(V) – is a diagonal matrix comprised of the eigenvalues along the
diagonal (sometimes represented with a capital lambda’Λ’)
and Q-1 is the inverse of the matrix comprised
of the eigenvectors.
EIGEN VALUE AND EIGEN VECTORS

● EIGENVECTORS - are unit vectors, (that their length or magnitude is equal


to 1.0).
● often referred as right vectors, which simply means a column vector
● A matrix that has only positive eigen values is -
a positive definite matrix.
● if the eigen values are all negative -a negative definite matrix.
EIGEN VALUE DECOMPOSITION
● Constituent parts to make certain operations
on the matrix easier to perform
● Used as an element to simplify the calculation of other more complex matrix
operations.
● Used to calculate the principal components of a matrix in the Principal
Component Analysis method (PCA) that can be used to reduce the
dimensionality of data in machine learning.
EIGEN VALUE DECOMPOSITION
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
w, v = np.linalg.eig(a)
print('Eigen values =')
print(w)
print ('Eigen vector =')
print(v)
SINGULAR VALUE DECOMPOSITION (SVD)
● a matrix decomposition method-reducing a matrix to its constituent parts
in order to make certain subsequent matrix calculations simpler.
● Provides another way to factorize a matrix, into provides another way to
factorize a matrix, into singular vectors and singular values.
● Allows us to discover some of the same kind of information as the Eigen
decomposition.
● Used in least squares linear regression, image compression, and denoising
data.
SINGULAR VALUE DECOMPOSITION (SVD)
● A method of decomposing a matrix into three other matrix
SINGULAR VALUE DECOMPOSITION (SVD)
import numpy as np
m = np.matrix([[1, 0, 0],
[1, 1, 0],
[0, 0, 1]])
u, s, v = np.linalg.svd(m)
print ('U =,')
print (u)
print ('S =')
print (s)
print ('V,=')
print (v)
PROGRAM WITH RECONSTRUCTED MATRIX
import numpy as np
m = np.matrix([[1, 0, 0],
[1, 1, 0],
[0, 0, 1]])
u, s, v = np.linalg.svd(m)
print ('U =,')
print (u)
print ('S =')
PROGRAM WITH RECONSTRUCTED MATRIX
print (s)
print ('V,=')
print (v)
mtilda= np.dot(u, np.dot(np.diag(s), v))
print('reconstructed matrix =')
print(mtilda)
PROGRAM WITH RECONSTRUCTED MATRIX
PROGRAM WITH RECONSTRUCTED MATRIX

You might also like