# How to multiply vector by number 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 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()




Laurent

more
{"ft_lang_label":"__label__en","ft_lang_prob":0.83422375,"math_prob":0.9611963,"size":944,"snap":"2019-51-2020-05","text_gpt3_token_len":338,"char_repetition_ratio":0.095744684,"word_repetition_ratio":0.11494253,"special_character_ratio":0.40677965,"punctuation_ratio":0.26190478,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9690423,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-12-12T23:41:59Z\",\"WARC-Record-ID\":\"<urn:uuid:2e0d4501-a393-4279-914e-a23c6bcf1b61>\",\"Content-Length\":\"58310\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:4ebb5bbd-f160-4924-96ab-361c1844f298>\",\"WARC-Concurrent-To\":\"<urn:uuid:9c56005a-a774-4100-8dcc-6fa4d20564eb>\",\"WARC-IP-Address\":\"140.254.118.68\",\"WARC-Target-URI\":\"https://ask.sagemath.org/question/8539/how-to-multiply-vector-by-number/\",\"WARC-Payload-Digest\":\"sha1:UASH5ZLVBEKGUQSRC5QW72DQNIVFRTFL\",\"WARC-Block-Digest\":\"sha1:S2HZWWIAAAY3AIJ7OVZER3TNVIXPPMHZ\",\"WARC-Identified-Payload-Type\":\"application/xhtml+xml\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-51/CC-MAIN-2019-51_segments_1575540547536.49_warc_CC-MAIN-20191212232450-20191213020450-00227.warc.gz\"}"}