Ask Your Question

How to create a nonzero vector?

asked 2017-06-12 17:07:02 +0100

ricom gravatar image

Hi. I would like to create a nonzero vector, for example, a vector of 100 elements of 1. I can do this with a for loop, but I'm not sure if there's a faster way to do it, similar to zero_vector(). Thanks.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2017-06-12 18:51:13 +0100

mforets gravatar image

here are some alternatives:

sage: %timeit vector([1. for i in range(1000)])
100 loops, best of 3: 3.14 ms per loop

sage: %timeit ones_matrix(RDF, 1000, 1)
125 loops, best of 3: 4.36 ms per loop

sage: %%time
....: v = zero_vector(RDF, 1000)
....: for i in range(1000):
....:     v[i] = 1
CPU times: user 2.39 ms, sys: 759 us, total: 3.15 ms
Wall time: 4.5 ms

just a list:

sage: %timeit [1. for i in range(1000)]
100 loops, best of 3: 2 ms per loop

with NumPy:

sage: import numpy as np
sage: %timeit np.ones(1000)
The slowest run took 9.23 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 3.9 us per loop
edit flag offensive delete link more

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


Asked: 2017-06-12 17:07:02 +0100

Seen: 211 times

Last updated: Jun 12 '17