You can move forward like this:
import numpy as np
matrix_a = np.array([
[0, 1, 1],
[2, 2, 0],
[3, 0, 3]
])
matrix_b = np.array([
[1, 1, 1],
[2, 2, 2],
[3, 2, 9],
[4, 4, 4],
[5, 9, 5]
])
Remember:
For matrix
multiplication , Order of first Column of matrix-A
== Order of first row of matrix-B
- Such as: B -> (3, 3) == (3, 5), to get order of column and row of matrices, you can use:
rows_of_second_matrix = matrix_b.shape[0]
columns_of_first_matrix = matrix_a.shape[1]
Here, you can check whether Order of first Column of matrix-A
== Order of first row of matrix-B
or not. If order is not same then go for transpose of matrix-B
, else simply multiply.
if columns_of_first_matrix != rows_of_second_matrix:
transpose_matrix_b = np.transpose(matrix_b)
output_1 = np.dot(matrix_a, transpose_matrix_b)
print('Shape of dot product:', output_1.shape)
print('Dot product:\n {}\n'.format(output_1))
output_2 = np.matmul(matrix_a, transpose_matrix_b)
print('Shape of matmul product:', output_2.shape)
print('Matmul product:\n {}\n'.format(output_2))
# In order to obtain -> Output_Matrix of shape (5, 3), Again take transpose
output_matrix = np.transpose(output_1)
print("Shape of required matrix: ", output_matrix.shape)
else:
output_1 = np.dot(matrix_a, matrix_b)
print('Shape of dot product:', output_1.shape)
print('Dot product:\n {}\n'.format(output_1))
output_2 = np.matmul(matrix_a, matrix_b)
print('Shape of matmul product:', output_2.shape)
print('Matmul product:\n {}\n'.format(output_2))
output_matrix = output_2
print("Shape of required matrix: ", output_matrix.shape)
Output:
- Shape of dot product: (3, 5)
Dot product:
[[ 2 4 11 8 14]
[ 4 8 10 16 28]
[ 6 12 36 24 30]]
- Shape of matmul product: (3, 5)
Matmul product:
[[ 2 4 11 8 14]
[ 4 8 10 16 28]
[ 6 12 36 24 30]]
- Shape of required matrix: (5, 3)