You need to multiply two square matrices: without using the built-in function NUMPY
That’s what happens to me:
for i in range (Len (a)): For j in Range (Len (A)): C [i] [j] = (a [i] [j] * b [i] [j]) Print (C, END = '') Print ()
But this multiplication is not a string on the column as needed, but elementary multiplication. How to implement multiplication of matrices string on a column according to the rules of mathematics?
Answer 1, Authority 100%
length = len (first_matrix) result_matrix = [[0 for i in Range (Length)] For i in Range (Length)] For i in Range (Length): For j in Range (Length): For k in Range (Length): result_matrix [i] [j] + = first_matrix [i] [k] * second_matrix [k] [j]
from typing import list DEF VEC_PRODUCT (VEC1: LIST [INT], VEC2: LIST [INT]) - & gt; Int: RETURN SUM ([INT (X * Y) for x, y in zip (vec1, vec2)]) Def Matrix_Transpose (Mat: List [List] - & gt; List [List]: Return [* Map (List, Zip (* Mat)]] DEF MATRIX_PRODUCT (MAT1: LIST [LIST [INT]], MAT2: LIST [LIST [INT]]): L, N = LEN (MAT1), LEN (MAT2 ) ANS = [[0 FOR I IN RANGE (N)] FOR J IN RANGE (L)] For i in Range (L): For j in Range (N): VEC1 = MAT1 [i] VEC2 = Matrix_Transpose (MAT2) [J] ANS [I] [J] = VEC_PRODUCT (VEC1, VEC2) Return ans.
In your program you need instead of
a [i] [j] * b [i] [j] Make:
the sum of all
a [i] [k] * b [k] [j], where
Len (A) - 1.
multiply perhaps even unquadant matrix, when:
- The number of columns of the first matrix The same as the number of rows of the second matrix,
- first matrix (
m × n(i.e.
ncolumns ), and
- second matrix (
n × k.
(the result will then be the matrix of type
m × k .)
I did just such a program – when you want it specifically only to multiply square matrices, delete the second and third string and in the rest of the part (instead of
k ) apply Only
m = len (a) # a: m × n n = len (b) # B: n × k K = Len (B ) C = [[[NONE FOR __ IN RANGE (K)] FOR __ IN RANGE (M)] # C: M × K For i in Range (M): For j in Range (k): C [i] [J] = SUM (A [I] [KK] * B [KK] [j] for kk in range (n)) Print (C)
2 × 3 ) and
3 × 4 ):
a = [[1, 1, 0], [1, 0, 2]] b = [[1, 0, 2, 1], [2, 1, 2, 0], [1, 1, 0, 3]]
The program displays as a result (correct) such matrix
2 × 4 ):
[[3, 1, 4, 1], [3, 2, 2, 7]]
For such a beautiful output, I did not use the
print () function , and
pprint () from the standard module
from pprint import pprint pprint (C, width = 15)
correctness is possible to check for example in NUMPY:
& gt; & gt; & gt; Import NUMPY AS NP & gt; & gt; & gt; NP.Array (A) @ B array ([[3, 1, 4, 1], [3, 2, 2, 7]])