Ask Your Question
0

element-wise operations

asked 2013-11-10 12:47:44 +0100

gundamlh gravatar image

In MATLAB element-wise operations:

link text

".*", ".^", "./" and so on.

In SAGE I have only found ".elementwise_product()". Are there any other element-wise operations on matrices, vectors, lists?

Thanks in advance!

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2013-11-10 13:55:19 +0100

tmonteil gravatar image

updated 2013-11-10 14:00:24 +0100

For lists, you can use list comprehension or the map function:

sage: [M[i] + N[i] for i in xrange(len(M))]
sage: map(operator.add, N, M)

For matrices, there is no such mechanism out of the box, but you can make one by yourself as follows:

def elementwise(operator, M, N):
    assert(M.parent() == N.parent())
    nc, nr = M.ncols(), M.nrows()
    A = copy(M.parent().zero_element())
    for r in xrange(nr):
        for c in xrange(nc):
            A[r,c] = operator(M[r,c], N[r,c])
    return A

and then use it as follows:

sage: elementwise(operator.add, M, N)
sage: elementwise(operator.pow, M, N)
sage: elementwise(operator.mul, M, N)
sage: elementwise(operator.div, M, N)

and so on.

edit flag offensive delete link more

Comments

Orz, so quick. Thanks

gundamlh gravatar imagegundamlh ( 2013-11-10 14:15:34 +0100 )edit

assert() is perhaps not a good choice for element-wise division? And why do you use xrange(), but not range()?

gundamlh gravatar imagegundamlh ( 2013-11-11 06:33:44 +0100 )edit

I believe that numpy arrays will do this automatically, however. Sage is built around mathematical constructs, but you can use Numpy from within Sage to do this.

kcrisman gravatar imagekcrisman ( 2013-11-11 11:25:44 +0100 )edit

Thanks! I am starting to learn NumPy.

gundamlh gravatar imagegundamlh ( 2013-11-22 11:46:57 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-11-10 12:47:44 +0100

Seen: 4,163 times

Last updated: Nov 10 '13