matrix Multiplication
Roberto Bonvallet
Roberto.Bonvallet at cern.ch
Wed Oct 18 08:59:47 EDT 2006
Sssasss wrote:
> hi evrybody!
>
> I wan't to multiply two square matrixes, and i don't understand why it
> doesn't work.
> Could you explain me?
>
> def multmat(A,B):
> "A*B"
> if len(A)!=len(B): return "error"
Wrong validation here: you _can_ multiply two matrices with a different
number of rows! And instead of returning "error" you should raise an
exception.
[...]
I suggest using a linear algebra package, but if you insist in using lists
of lists:
>>> b = [[1, 2, 3, 4],
... [4, 5, 6, 7],
... [7, 8, 9, 10]]
>>>
>>> a = [[1, 2, 3],
... [4, 5, 6]]
>>>
>>> ab = [[sum(i*j for i, j in zip(row, col)) for col in zip(*b)] for row in a]
>>> ab
[[30, 36, 42, 48], [66, 81, 96, 111]]
Straightforward from the definition of matrix multiplication.
--
Roberto Bonvallet
More information about the Python-list
mailing list