Ask Your Question
1

How to multiply vector by number

asked 2011-12-13 20:25:23 -0500

anonymous user

Anonymous

I have vector

W = [1, 8, 4, 7, 10, 1, 6, 3]

I need to multiply it by number, but command 2*W gives just concatenated vector by itself

[1, 8, 4, 7, 10, 1, 6, 3, 1, 8, 4, 7, 10, 1, 6, 3]

I dont need it, I need multiply all elements of vector to number

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
2

answered 2011-12-13 21:30:11 -0500

updated 2011-12-13 21:37:29 -0500

This behaviour is part of Python (the following code is evaluated in the standard python shell, although it should also work in sage or a sage notebook):

>>> W = [1, 8, 4, 7, 10, 1, 6, 3]
>>> 2*W
[1, 8, 4, 7, 10, 1, 6, 3, 1, 8, 4, 7, 10, 1, 6, 3]

The standard thing to do is to either use list comprehension

>>> [3*i for i in W]
[3, 24, 12, 21, 30, 3, 18, 9]

or map (for a comparison, see http://stackoverflow.com/q/1247486/42...)

>>> map(lambda i: 3*i, W)
[3, 24, 12, 21, 30, 3, 18, 9]

Although, if you're using just numerical lists and are used to matlab, then maybe you should use numpy:

>>> import numpy
>>> npW = numpy.array(W)
>>> npW*3
array([ 3, 24, 12, 21, 30,  3, 18,  9])

For large arrays, NumPy will be faster at this type of operation than the pythonic methods above. For a discussion of NumPy in sage see http://www.sagemath.org/doc/numerical...


Of course, the standard sage approach is to use a vector object (see Laurent's answer)

edit flag offensive delete link more
5

answered 2011-12-13 21:18:24 -0500

Your W is not a vector but a list. If you want a vector you have to do the following :

sage: v=vector([1,2])
sage: v
(1, 2)
sage: 3*v
(3, 6)
sage: 
sage: v.column()
[1]
[2]

Laurent

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

Stats

Asked: 2011-12-13 20:25:23 -0500

Seen: 987 times

Last updated: Dec 13 '11