On Sun, 07 Jun 2009 at 11:12AM -0700, paramaniac wrote:
> Is there a possibility/workaround in Sage to compute the element-wise
> multiplication of two matrices? In Matlab there's the .* operator, but
> Matlab is useless in my case since I need a symbolic result.

There's no operator that I know of for that, but you can convert your
matrices to lists, multiply, and convert back:

sage: x,y,z,w = var('x y z w')
sage: a = matrix(SR, 2, 2, [x, y, z, w])
sage: b = matrix(SR, 2, 2, [1+x, 1+y, 1+z, 1+w])
sage: a.list()
[x, y, z, w]
sage: b.list()
[x + 1, y + 1, z + 1, w + 1]

Now make a list of corresponding pairs of entries with zip() and
multiply:

sage: [ x*y for x, y in zip(a.list(), b.list()) ]
[(x + 1)*x, (y + 1)*y, (z + 1)*z, (w + 1)*w]

...and make a matrix out of the new list:

sage: matrix(2, 2, [ x*y for x, y in zip(a.list(), b.list()) ])

[(x + 1)*x (y + 1)*y]
[(z + 1)*z (w + 1)*w]

You can easily put that sequence of steps into a function. You may need
to fiddle a bit with the rows and columns bits, and maybe add a ring
argument if you need to specify what ring the matrix should be over.

def componentwise_multiply(a, b, rows, cols):
    return matrix(rows, cols, [x*y for x, y in zip(a.list(), b.list())])


Dan

-- 
---  Dan Drake <dr...@kaist.edu>
-----  KAIST Department of Mathematical Sciences
-------  http://mathsci.kaist.ac.kr/~drake

Attachment: signature.asc
Description: Digital signature

Reply via email to