# element-wise operations

In MATLAB element-wise operations:

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

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

edit retag close merge delete

Sort by » oldest newest most voted

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

sage: [M[i] + N[i] for i in xrange(len(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.

more

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

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.