In: Computer Science
Write a program which reads the matrix A (2x2 matrix taking the first two column vectors from the input file) and the vector b (the third column vector) and solve for x in Ax=b for general A.
If there is a unique solution, your output should be a 2x2 matrix with two lines and two numbers per line. The output should contain numbers with up to four significant digits. If the system is unsolvable or inconsistent, then your output should be a single line printing "System inconsistent". If the system is underdetermined, your output should be a single line printing "System underdetermined".
Input format (2x3 matrix):
n11 n12 n13
n21 n22 n23
In python please
ANSWER:
CODE
# import important module
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])
# checking if size of A and b no equal
m,n = len(A),len(A[0])
sizeB = len(b)
if (m!=n) or (n!=sizeB):
print("System underdetermined")
else:
# otherwise, solving equation using np.linalg.solve
# catching error if singular matrix
try:
# using np.linalg.solve to solve equaion
X2 = np.linalg.solve(A,b)
# displaying result, diagonal matrix of X2 for 2x2 matrix display
print("{:.4f} {:.4f}\n{:.4f} {:.4f}".format(*np.diag(X2).flatten()))
except np.linalg.LinAlgError as err:
if 'Singular matrix' in str(err):
print('System inconsistent')
else:
# otherwise
raise
INPUT IMAGE (matrix.txt)
OUTPUT IMAGE