In: Computer Science
Given the matrix A (2x2 matrix taking the first two column vectors from the input file), compute the followings. Λ: the diagonal matrix whose diagonal elements are the corresponding eignevalues Λii = λi for i=1,2 R: the 2x2 matrix whose ith column vector is the eigenvector corresponding to λi for i=1,2 RΛRT: the matrix compositions 1/0: the comparison between A and RΛRT (is A= RΛRT?) Your output should have seven lines where the first two lines correspond to the 2x2 matrix of Λ, the next two lines is R, and the last two lines is the output matrix of RΛRT, and the last line is one binary number corresponding to yes (1) or no (0). The first six lines have two numbers per line, while the last line has one binary number. The output should contain numbers with up to four significant digits. If there is one real eigenvalue (λ1=λ2), then the two column vectors for R are the same, and your output should be of the aforementioned format. If there are no real eigenvalues, your output should be a single line printing "No real eigenvalues".
Input format (2x3 matrix):
n11 n12 n13
n21 n22 n23
In python please
ANSWER:
CODE
import numpy as np
# reading input file "matrix.txt"
inputFile = open("matrix.txt")
# defining empty matrix A and b
A = []
b = []
# looping through each line and converting input to matrix
for line in inputFile:
# spliting line and converting each value to float
row = [int(c) for c in line.split()]
# first two values to A
A.append(row[:2])
# and last to b
b.append(row[2])
# eigen values and matrix using numpy.linalg.eig function
[V, R] = np.linalg.eig(A)
# converting eigen values V to diagonal matrix, using np.diag function
V = np.diag(V)
# calculating RVRT,using np.dot to multiply matrix
RV = np.dot(R,V)
RVRT = np.dot(RV, R.T)
# displaying result
# displaying result, diagonal matrix of V for 2x2 matrix display
print("{:.4f} {:.4f}\n{:.4f} {:.4f}".format(*V.flatten()))
# displaying result, diagonal matrix of R for 2x2 matrix display
print("{:.4f} {:.4f}\n{:.4f} {:.4f}".format(*R.flatten()))
# displaying result, diagonal matrix of RVRT for 2x2 matrix display
print("{:.4f} {:.4f}\n{:.4f} {:.4f}".format(*RVRT.flatten()))
# comparing RVRT to A and finding if all values of both matrix match using np.all
# finaly converting bool to int using int function
print(int(np.all(RVRT == A)))
INPUT IMAGE (matrix.txt)
OUTPUT IMAGE