I implemented a function in Python to calculate the matrix multiplication, vector inner product, transposed matrix, and matrix product.
matrix.py
#!/usr/bin/env python
# -*- coding : utf-8 -*-
def get_matrix_scalar_mul(matrix, n):
if isinstance(matrix[0], list):
return [get_matrix_scalar_mul(matrix[i], n) for i in range(len(matrix))]
return [x*n for x in matrix]
def get_inner_prod(raw, col):
return sum([x*y for (x,y) in zip(raw,col)])
def get_matrix_trans(matrix):
# malloc n*m matrix
matrix_t = [[0 for j in range(len(matrix))] for i in range(len(matrix[0]))]
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrix_t[j][i] = matrix[i][j]
return matrix_t
def get_matrix_mul(matrix1, matrix2):
# malloc A_m*B_n matrix
result = [[0 for j in range(len(matrix2[0]))] for i in range(len(matrix1))]
matrix2_t = get_matrix_trans(matrix2)
for i in range(len(result)):
for j in range(len(result[0])):
result[i][j] = get_inner_prod(matrix1[i], matrix2_t[j])
return result
if __name__ != '__main__':
exit(None)
#
# main
#
A = [ [1,2], \
[0,1], \
[5,1]]
B = [[1,-2,4,0], \
[0,-1,2,3]]
print '2A = '
print get_matrix_scalar_mul(A, 2)
print 'A x B = '
print get_matrix_mul(A, B)
exit(None)
Execution result
$ python sample.py
A =
[[1, 2], [0, 1], [5, 1]]
B =
[[1, -2, 4, 0], [0, -1, 2, 3]]
2A =
[[2, 4], [0, 2], [10, 2]]
A_t =
[[1, 0, 5], [2, 1, 1]]
A x B =
[[1, -4, 8, 6], [0, -1, 2, 3], [5, -11, 22, 3]]
Recommended Posts