First time here? Check out the FAQ!

Ask Your Question
1

How do I do map/element-wise operations?

asked 3 years ago

apromixately gravatar image

I am looking for a way to apply a function to every element of a vector or matrix.

v = vector([2, 0, -3])
print(v)
w = sign(v)
print(w) # I want (1, 0, -1)

m = matrix([[1, 2], [3, 4]])
m = m**2
print(m) # I want [1, 4] [9, 16]

How does this work?

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
3

answered 3 years ago

tmonteil gravatar image

You can use the apply_map method :

sage: v.apply_map(sign)
(1, 0, -1)

sage: m.apply_map(lambda x : x^2)
[ 1  4]
[ 9 16]
Preview: (hide)
link

Your Answer

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

Add Answer

Question Tools

1 follower

Stats

Asked: 3 years ago

Seen: 399 times

Last updated: Dec 18 '21