In: Computer Science
Write a function matrix power(A, n) that computes the power An using Boolean arithmetic and returns the result. You may assume that A is a 2D list containing only 0s and 1s, A is square (same number of rows and columns), and n is an integer ≥ 1. You should call your previously written matrix multiply boolean function.
Example: Let R = [ [0, 0, 0, 1], [0, 1, 1, 0], [0, 0, 0, 1], [0, 0, 1, 0] ]
Then calling matrix power(R, 2) should return [ [0, 0, 1, 0], [0, 1, 1, 1], [0, 0, 1, 0], [0, 0, 0, 1] ]
We initialized a boolean matrix and call the function matric_power(A,n) for calculating A^n.
Program:
Output of the program:
Source Code :
import numpy as np
# Function that using boolean arithmetic to calculate A^n
def matrix_power(A, n):
R = A
for i in range(n-1): #Loop calculates R = A^n
R = R*A
return R #It Returns the result
#Initializing 2D list A
A = np.matrix([[0,0,0,1], [0,1,1,0], [0,0,0,1], [0,0,1,0]],
dtype=bool)
R = matrix_power(A,2) #Calling the function
print("Result is")
print(R.astype(int)) #Printing the result