Division matrix

Ian Kelly ian.g.kelly at gmail.com
Tue Nov 13 02:25:33 CET 2012

On Mon, Nov 12, 2012 at 6:00 PM, Cleuson Alves <cleuson.o at gmail.com> wrote:
> Hello, I need to solve an exercise follows, first calculate the inverse matrix and then multiply the first matrix.
> I await help.
> Thank you.
> follows the code below incomplete.

So what is the specific problem with the code that you're looking for help with?

> m = [[1,2,3],[4,5,6],[7,8,9]]
> x = []
> for i in [0,1,2]:
>     y = []
>     for linha in m:
>         y.append(linha[i])
>     x.append(y)
> print x
> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

This calculates the transpose of the matrix, not the inverse.  If the
inverse is really what you're after, you should start by reading up on
the math to compute that.

Note that "for i in [0,1,2]:" could be more generally written as "for
i in range(len(m[0])):", and then you don't need to rewrite your for
loop if the dimensions of m change.

If you actually do want the transpose, then I'll also mention in
passing that there is a very nice one-liner using zip() to do this.
I'll leave the details as an exercise. ;-)

> def ProdMatrix(x,b):
>     tamL = len(x)
>     tamC = len(x[0])
>     c = nullMatrix(tamL,tamC)
>     for i in range(tamL):
>         for j in range(tamC):
>             val = 0
>             for k in range(len(b)):
>                 val = val + x[i][l]*b[k][j]
>             c[i][j]
>     return c

In the multiplication line you're using the variable 'l' as an index,
but you haven't defined it.  Probably you wanted 'k' here.

You're also discarding 'val' after adding it up.  If you want that
value in the 'c' matrix, then you need to store it there before going
on to the next loop.

More information about the Python-list mailing list