Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save calloc134/74027d2e9d7dfba0858f67622ee6c485 to your computer and use it in GitHub Desktop.

Select an option

Save calloc134/74027d2e9d7dfba0858f67622ee6c485 to your computer and use it in GitHub Desktop.
行列計算実装 Python
# 4*4の行列計算の過程を表示するプログラム
# 平方根にも対応
from sympy import sqrt
def print_matrix(a_matrix):
print("this matrix =")
for i in range(a_matrix.__len__()):
for j in range(a_matrix[i].__len__()):
print("{:.3f}".format(a_matrix[i][j]), end=" ")
print()
print()
# 行列は二次元配列で表示される
# 4*4の行列の場合、4行4列の二次元配列となる
def print_matrix_sympy(a_matrix, b_matrix):
# 行列の掛け算
# 結果を格納する配列
result_matrix = []
for a_row in range(len(a_matrix)):
result_matrix.append([])
for b_col in range(len(b_matrix[0])):
result_matrix[a_row].append(0)
for b_col in range(len(b_matrix[0])):
for a_row in range(len(a_matrix)):
# 計算した要素を格納する配列
# 後ほど合計する
array = []
for n in range(len(a_matrix[a_row])):
if n != 0:
print("+", end=" ")
first = a_matrix[a_row][n]
second = b_matrix[n][b_col]
value = first * second
array.append(value)
if value != 0:
# カラーコードは青
print(
"\033[34m{:.3f} * {:.3f}".format(first, second),
end=" ",
)
else:
print(
"\033[0m{:.3f} * {:.3f}".format(first, second),
end=" ",
)
# カラーコードも工夫
# print("= {:3d}".format(sum(array)), end=" ")
print("= \033[31m{:.3f}\033[0m".format(sum(array)), end=" ")
result_matrix[a_row][b_col] = sum(array)
print()
print()
return result_matrix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment