# How to multiply vector by number

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

Sort by ยป oldest newest most voted

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)

more

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

more