## define the matrix multiply function
def multiply_matrix(matrix,n):
result=[]
for i in range(n):
rows=[]
for j in range(n):
column=[a[j] for a in matrix]
ans=0
for m in range(n):
ans+=matrix[i][m]*column[m]
rows.append(ans)
result.append(rows)
return result
##read matrix file
matrix=[]
with open('./matrix.txt', 'r') as f:
for line in f:
list_=[]
for i in line.split():
i=int(i)
list_.append(i)
matrix.append(list_)
n=len(matrix[0])
print(f"The matrix is {matrix}")
print(f"The dimension of the input matrix is {n}")
## calculation
for i in range(2):
matrix=multiply_matrix(matrix,n)
print(f"The 4th power of Matrix is {matrix}")
##write the result into power_matrix file
with open('./power_matrix.txt', 'w') as f:
for line in matrix:
for i in range(n):
f.write(str(line[i]))
f.write(" ")
f.write("\n")
f.close()
python实现矩阵相乘 计算矩阵的四次幂
最新推荐文章于 2022-09-16 21:22:52 发布