# How to calculate element-wise matrix functions in Sage

Anonymous

In MATLAB one can write:

A = [1,2,3]; B = 2*A.^3;

where B gets element-wise result of the function 2*A.^3 given matrix (or vector) A.

In Sage the notation .^ does not function. How to do this in Sage?

Then how to calculate the element-wise sin(A) in Sage?

edit retag close merge delete

Sort by ยป oldest newest most voted
sage: A = vector([1,2,3])
(1, 8, 27)
sage: A.apply_map(2*x^3)
(2, 16, 54)
sage: A.apply_map(sin(x))
(sin(1), sin(2), sin(3))


Note that the first time you do this you might get a warning.

sage: A.apply_map(x^3)
/Users/.../sage-5.8.beta3/local/lib/python2.7/site-packages/IPython/core/interactiveshell.py:2721: DeprecationWarning: Substitution using function-call syntax and unnamed arguments is deprecated and will be removed from a future release of Sage; you can use named arguments instead, like EXPR(x=..., y=...)
See http://trac.sagemath.org/5930 for details.
exec code_obj in self.user_global_ns, self.user_ns


So you wouldn't want to rely on that syntax long-term. There are several ways around this; here's one.

sage: A = vector([1,2,3])
sage: A.apply_map(lambda x: sin(x))
(sin(1), sin(2), sin(3))

more

I don't think Sage has the elementwise matrix operations as it is used in MATLAB, but numpy has. So, the OP can either use numpy directly (it is vectorized), or use the Sage equivalent for the Schur product. Elementwise matrix products (Schur product) are present in Sage, and can be accessed by using A.elementwise_product(B), where A, B are matrices. However, the elementwise operations in MATLAB are a bit different. When we write A.^3 MATLAB actually considers 3 to be a matrix B = 3*ones(size(A)). And, then it does A.^B. Here, B can be any other matrix of the same dimensions as A. I think this (vectorized) elementwise power is not present in Sage.

( 2013-03-12 11:52:03 +0100 )edit