Created
June 28, 2025 08:24
-
-
Save sina-programer/8d034a95ad414182b29ba645834cce5d to your computer and use it in GitHub Desktop.
matrix multiplication implemented in python from scratch without arrays.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def matrix_multiplication(A, B): | |
m = len(A) | |
n = len(A[0]) | |
n2 = len(B) | |
k = len(B[0]) | |
assert n == n2 | |
assert all(len(row)==n for row in A) | |
assert all(len(row)==k for row in B) | |
matrix = [] | |
for i in range(m): | |
row = [] | |
for j in range(k): | |
row.append( | |
sum( | |
A[i][c] * B[c][j] | |
for c in range(n) | |
) | |
) | |
matrix.append(row) | |
return matrix | |
if __name__ == "__main__": | |
from pprint import pprint | |
A = [ | |
[1, 2], | |
[1, 3] | |
] | |
B = [ | |
[1, 0], | |
[0, 1] | |
] | |
print('A:') | |
pprint(A) | |
print() | |
print('B:') | |
pprint(B) | |
print() | |
print('A.B:') | |
pprint(matrix_multiplication(A, B)) | |
print() | |
print('B.A:') | |
pprint(matrix_multiplication(B, A)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment