Ask Your Question

How to calculate element-wise matrix functions in Sage

asked 2013-03-12 04:01:36 -0500

anonymous user


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 flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2013-03-12 04:45:42 -0500

kcrisman gravatar image
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/ 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 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))
edit flag offensive delete link 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.

ppurka gravatar imageppurka ( 2013-03-12 05:52:03 -0500 )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


Asked: 2013-03-12 04:01:36 -0500

Seen: 594 times

Last updated: Mar 12 '13