matrix Multiplication
Sssasss
reivax85 at gmail.com
Wed Oct 18 19:01:24 CEST 2006
Roberto Bonvallet wrote:
> 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
Thank you, this one is very short!
yes of course we can multiply different kinds of matrices, bu since
I'm starting with python i started with something quick.
ciao
More information about the Python-list
mailing list