Ask Your Question
1

How to multiply vector by number

asked 13 years ago

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

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
2

answered 13 years ago

updated 13 years ago

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)

Preview: (hide)
link
5

answered 13 years ago

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

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

Stats

Asked: 13 years ago

Seen: 19,341 times

Last updated: Dec 14 '11