You are on page 1of 21

LAB 4: REALIZATION OF ARRAYS AND MATRICES

AIM:
● Realization and visualizations of matrix and arrays
● Obtain stem and continuous plots of real arrays using matplotlib
● Computation of inverse of square matrix, solution of matrix equation,
rank of matrix, eigen values and eigen vectors.
● Understanding singular value decomposition and its application.

Singular Value Decomposition


Singular value decomposition (SVD) is a method of representing a matrix as a
series of linear approximations that expose the underlying meaning-structure of
the matrix. The goal of SVD is to find the optimal set of factors that best predict
the outcome. During data pre-processing prior to text mining operations, SVD is
used in latent semantic analysis (LSA) to find the underlying meaning of terms in
various documents.
In more technical terms, SVD is closely related to principal component
analysis in that it reduces the overall dimensionality of the input matrix (number
of input documents by number of extracted terms) to a lower dimensional space
(a matrix of much smaller size with fewer variables), where each consecutive
dimension represents the largest degree of variability (between terms and
documents) possible (Manning and Schutze, 1999). Ideally, the analyst might
identify the two or three most salient dimensions that account for most of the
variability (differences) between the terms and documents, thus identifying the
latent semantic space (is this term the same as lower dimensional space?) that
organizes the terms and documents in the analysis. When these dimensions are
identified, they represent the underlying “meaning” of what is contained
(discussed or described) in the documents. For example, assume that
matrix A represents an m × n term occurrence matrix, where m is the number of
input documents and n is the number of terms selected for analysis. The SVD
computes the m × r orthogonanal matrix U, n × r orthogonal matrix V,
and r × r matrix D, so A = UDV’ and r is the number of eigenvalues of A’A.

Applications of the SVD

o Pseudoinverse
o Solving homogeneous linear equations
o Total least squares minimization
o Range, null space and rank
o Low-rank matrix approximation
o Separable models
o Nearest orthogonal matrix
o The Kabsch algorithm
o Signal processing

Experiment 1
AIM: To realize one dimensional array [1, 4, 16, 32], obtain the continuous and
discrete plots of the above array and upload the results.
ALGORITHM

1. START
2. Import matplotlib.pyplot
3. Initialize the given array
4. Declare plot function to plot continuous graph[(plt.plot(x))] and
discrete graph[plt.plot(x,’ob’)
5. Declare show function to display the plot
6. STOP

CODE
import matplotlib.pyplot as plt
a=[1,4,16,32] #realiize matrix
plt.plot(a) #plot continuous graph
plt.ylabel('some numbers') #label axis
plt.show() #display graph
plt.stem(a) #plot discrete graph
plt.ylabel('some numbers') #label axis
plt.show() #display graph
OUTPUT
Experiment 2

AIM: To realize the matrix given matrix x and obtain its visualization

ALGORITHM
STEP1: START
STEP2: Import matplotlib.pyplot as plt
STEP3: Initialise the givenarray
STEP4: Use the function plt.imshow() to visualise the matrix
STEP5: Declare the show function to display the visualisation
STEP6: STOP
CODE
import matplotlib.pyplot as plt
a=[[1,2,3],[3,2,1],[1,0,-1]] #realize matrix
plt.imshow(a) #render matrix into pixels
plt.show() #display image
OUTPUT
Experiment 3

AIM: To find the inverse of the given matrix x

ALGORITHM
1. START
2. Import the package numpy as np
3. The array is initialized using numpy and stored in variable x.
4. The array is inversed using the function[np.linalg.inv(x)] .
5. Inversed array is stored in variable y.
6. Now print both array x and y.
7. STOP
CODE
import numpy as np
x = np.array([[1,3,3],[1,4,3],[1,3,4]]) #realize matrix
print("Original matrix:")
print(x) #display original matrix
y = np.linalg.inv(x) #calculate inverse
print("Inverse of the given matrix:")
print(y) #display output
OUTPUT
Experiment 4
AIM: To solve the given system of linear equations using matrix
USING ‘solve()’ FUNCTION
ALGORITHM
1. START
2. Import numpy as np
3. Initialize two matrices A[with coefficients of x,y and z] and B[with constants]
4. Solve using [X=np.linalg.solve(A,B)]
5. Print the solution matrix X
6. STOP

CODE
import numpy as np
A = np.array([[2, 1, -1], [1, 3, 2], [1, 0, 0]]) #realize matrix of coefficients
B = np.array([4,5,6]) #realize matrix of constants
x = np.linalg.solve(A, B) #solve linear equations
print(x) #display output
OUTPUT

WITHOUT USING ‘solve()’ FUCTION


ALGORITHM

1. START
2. Import numpy as np
3. Initialize two matrices A[with coefficients of x,y and z] and B[with constants]
4. Import the matrices to numpy array
5. Solve using inverse function and dotfunctions[X=np.linalg.inv(A).dot(B)]
6. Print the solution matrix X
7. STOP
CODE
import numpy as np
A = np.array([[2, 1, -1], [1, 3, 2], [1, 0, 0]]) #realize matrix of coefficients
BaseException = np.array([4,5,6]) #realize matrix of constants
x=np.linalg.inv(A) #find inverse of A
res=x.dot(B) # X=A^(-1).B
print(res) #display output
OUTPUT
Experiment 5
AIM: To find the rank of the given matrix
ALGORITHM
1. START
2. Import numpy as np
3. Initialize the arrays using numpy and store in variable x
4. Rank of the array is found using np.linalg.matrix_rank(x).
5. Print the result.
6. STOP
CODE
import numpy as np
x = np.array([[1,2,3], [3,2,1], [1, 0, -1]])
y = np.array([[-4,-3,2], [1,2,1], [2,4,2]]) #realize matrices
print("Matrix x is \n",x)
rx = np.linalg.matrix_rank(x) #find rank of x
print("Rank of Matrix x: ",rx) #display rank of x
OUTPUT
AIM: To find the eigen values of the given matrix x
ALGORITHM
1. START
2. from numpy.linalg import eig.
3. import numpy as np.
4. x=np. array([[10,20,30,40],[1,2,3,5],[7,8,9,10],[15,25,35,45]])
5. value = eig(x)
6. print(values)
7. STOP
CODE
import numpy as np
x = np.array([[1,2,3], [3,2,1], [1, 0, -1]])
y = np.array([[-4,-3,2], [1,2,1], [2,4,2]]) #realize matrices
eix=np.linalg.eig(x) #finding eigen value
print("Eigen values of x: ",eix[0]) #displaying eigen value

OUTPUT
AIM: To find eigen vectors of the given matrix x
ALGORITHM
1. START
2. from numpy.linalg import eig.
3. import numpy as np.
4. x=np. array([[10,20,30,40],[1,2,3,5],[7,8,9,10],[15,25,35,45]])
5. vector = eig(x)
6. print(vector)
7. STOP
CODE
import numpy as np
x = np.array([[1,2,3], [3,2,1], [1, 0, -1]])
y = np.array([[-4,-3,2], [1,2,1], [2,4,2]]) #realize matrices
eix=np.linalg.eig(x) #finding eigen vectors
print("Eigen vector of x \n",eix[1]) #displaying eigen vectors
OUTPUT
AIM: To find the rank of the given matrix y
ALGORITHM
1. Start
2. Import numpy as np
3. Initialize the arrays using numpy and store in variable y
4. Rank of the array is found using np.linalg.matrix_rank(y).
5. Print the result.
6. Stop
CODE
import numpy as np
x = np.array([[1,2,3], [3,2,1], [1, 0, -1]])
y = np.array([[-4,-3,2], [1,2,1], [2,4,2]]) #realize matrices
print("Matrix y is \n",y)
ry = np.linalg.matrix_rank(y) #finding the rank
print("Rank of Matrix y: ",ry) #displaying result

OUTPUT
AIM: To find the eigen values of the given matrix y
ALGORITHM
1. START
2. from numpy.linalg import eig.
3. import numpy as np.
4. y=np. array([[10,20,30,40],[1,2,3,5],[7,8,9,10],[15,25,35,45]])
5. value = eig(y)
6. print(values)
7. STOP
CODE
import numpy as np
x = np.array([[1,2,3], [3,2,1], [1, 0, -1]])
y = np.array([[-4,-3,2], [1,2,1], [2,4,2]]) #realize matrices
eiy=np.linalg.eig(y) #finding eigen values
print("Eigen values of y: ",eiy[0]) #displaying eigen value
OUTPUT

AIM: To find the eigen vectors of the given matrix y


ALGORITHM
1. START
2. from numpy.linalg import eig.
3. import numpy as np.
4. y=np. array([[10,20,30,40],[1,2,3,5],[7,8,9,10],[15,25,35,45]])
5. vector = eig(y)
6. print(vector)
7. Stop
CODE
import numpy as np
x = np.array([[1,2,3], [3,2,1], [1, 0, -1]])
y = np.array([[-4,-3,2], [1,2,1], [2,4,2]]) #realize matrices
eiy=np.linalg.eig(y) #finding eigen vectors
print("Eigen vector of y \n",eiy[1]) #displaying eigen vectors
OUTPUT
Experiment 6
AIM: To perform the singular value decomposition of the given matrix and
print the left singular matrix, right singular matrix, eigen value matrix and to
reconstruct the matrix using all singular vectors obtained from svd.
CODE
import numpy as np # importing numpy
A = np.array([[1,0,0],[1,1,0],[0,0,1]]) #initialising the array
u,s,v= np.linalg.svd(A) #decomposes the matrix A into u,s and v
print("left singular matrix ") #prints left singular matrix
print(u)
print("right singular matrix") #prints right singular matrix
print(v)
print("matrix with eigen values") #prints matrix with eigen values
print(s)
np.diag(s) #forms the diagonal matrix of s
print("reconstructed matrix") #matrix reconstruction
print(np.dot(u,np.dot(np.diag(s),v)))
OUTPUT
Experiment 7
AIM: To perform the singular value decomposition of the given matrix and
print the left singular matrix, right singular matrix, eigen value matrix
CODE
import numpy as np # importing numpy
A = np.array([[2,0,8,6,0],[1,6,0,1,7],[5,0,7,4,0],[7,0,8,5,0],[0,10,0,0,7]])
u,s,v= np.linalg.svd(A) #decomposes the matrix A into u,s and v
print("left singular matrix ") #prints left singular matrix
print(u)
print("right singular matrix") #prints right singular matrix
print(v)
print("matrix with eigen values") #prints matrix with eigen values
print(s)
OUTPUT
AIM: To reconstruct the matrix using first 2 singular vectors obtained from SVD
and to obtain the absolute error
CODE
import numpy as np #importing numpy
A = np.array([[2,0,8,6,0], [1,6,0,1,7], [5,0,7,4,0],[7,0,8,5,0],[0,10,0,0,7]])
u,s,v = np.linalg.svd(A) #decomposes the matrix A into u, s and v
n = int(input("Enter the number of vectors \n"))
Sigma = np.zeros((n,n))
Sigma[:n, :n] =np.diag(s)[0:n,0:n]
B= u[:,0:n].dot(Sigma.dot(v[0:n,:]))
print("reconstructed matrix")
print(B)
print("absolute error")
print(np.linalg.norm(A - B))
OUTPUT
AIM: To reconstruct the matrix using first 3 singular vectors obtained from SVD
and to obtain the absolute error
CODE
import numpy as np #importing numpy
A = np.array([[2,0,8,6,0], [1,6,0,1,7], [5,0,7,4,0],[7,0,8,5,0],[0,10,0,0,7]])
u,s,v = np.linalg.svd(A) #decomposes the matrix A into u, s and v
n = int(input("Enter the number of vectors \n"))
Sigma = np.zeros((n,n))
Sigma[:n, :n] =np.diag(s)[0:n,0:n]
B= u[:,0:n].dot(Sigma.dot(v[0:n,:]))
print("reconstructed matrix")
print(B)
print("absolute error")
print(np.linalg.norm(A - B))
OUTPUT
AIM: To reconstruct the matrix using first 4 singular vectors obtained from SVD
and to obtain the absolute error
CODE
import numpy as np #importing numpy
A = np.array([[2,0,8,6,0], [1,6,0,1,7], [5,0,7,4,0],[7,0,8,5,0],[0,10,0,0,7]])
u,s,v = np.linalg.svd(A) #decomposes the matrix A into u, s and v
n = int(input("Enter the number of vectors \n"))
Sigma = np.zeros((n,n))
Sigma[:n, :n] =np.diag(s)[0:n,0:n]
B= u[:,0:n].dot(Sigma.dot(v[0:n,:]))
print("reconstructed matrix")
print(B)
print("absolute error")
print(np.linalg.norm(A - B))
OUTPUT
AIM: To reconstruct the matrix using first 5 singular vectors obtained from SVD
and to obtain the absolute error.
CODE
import numpy as np #importing numpy
A = np.array([[2,0,8,6,0], [1,6,0,1,7], [5,0,7,4,0],[7,0,8,5,0],[0,10,0,0,7]])
u,s,v = np.linalg.svd(A) #decomposes the matrix A into u, s and v
n = int(input("Enter the number of vectors \n"))
Sigma = np.zeros((n,n))
Sigma[:n, :n] =np.diag(s)[0:n,0:n]
B= u[:,0:n].dot(Sigma.dot(v[0:n,:]))
print("reconstructed matrix")
print(B)
print("absolute error")
print(np.linalg.norm(A - B))
OUTPUT
AIM: To plot the absolute error against r, where r is the number of singular
vectors used for matrix reconstruction.
CODE
import numpy as np #import numpy
import matplotlib.pyplot as plt #import matplotlib.pyplot
A = np.array([[2,0,8,6,0],[1,6,0,1,7],[5,0,7,4,0],[7,0,8,5,0],[0,10,0,0,7]])
u,s,v= np.linalg.svd(A)
abs = []
# Iterate over sequence of numbers from 0 to 9
# Append each number at the end of list for
r in range(1,6):
Sigma=np.zeros((r,r))
Sigma =np.diag(s)[0:r,0:r]
B=np.dot(u[:,0:r],np.dot(Sigma,v[0:r,:]))
abs.append(np.linalg.norm(A - B))
OUTPUT

RESULT:
Understood the needs and requirements of scientific computing and
familiarized python language for scientific computing

You might also like