Reputation: 21
I want to multiply a vector by a scalar by a cicle, i.e:
x1=[2,3,4,5]
and i want to multiply it by 2, so that i get, x1=2(x2)
, x2=[4,6,8,10]
.
I tried doing this:
def multiplicar_vector(x1):
x2=[]
for i in x1:
x2[i] = (x1[i])*2
print(x2)
But it doesn't work.
Upvotes: 1
Views: 9410
Reputation: 2484
There is a python package that does this really well : numpy
import numpy as np
x2 = np.array(x1)*2
Upvotes: 0
Reputation: 1112
You can iterate through each item and multiply it
x1=[2,3,4,5]
N=2
x2 = [ x * N for x in x1]
print(x2)
Incase you want to use a predefined package. Convert your list vector type into a numpy vector array type and multiply.
import numpy as np
x1=[2,3,4,5]
N=2
my_array = np.array(x1)
x2 = my_array * N
print(x2)
Upvotes: 0
Reputation: 1093
If you want to use pure python, you would likely use a list comprehension.
x1 = [item * 2 for item in x2]
This is taking each item in the x2, and multiplying it by 2. The square brackets indicate that you want to make a list of the results. It's equivalent to:
x1 = []
for item in x2:
x1.append(item * 2)
Really though, most people would use numpy when dealing with lots of vectors as it much faster and easier.
import numpy as np
x1 = np.array([1, 2, 3, 4])
x2 = 2 * x1
Upvotes: 2