BaRud
BaRud

Reputation: 3230

weighted sum of vector of unknown dimension

I am trying to get a weighted sum of vectors(dimension of vect is variable), with data as:

vect[1] = [5., 6., 7.]    mult[1][1] = "20" 
vect[2] = [7., 8., 9.]    mult[2][1] = "80"
......

what I am looking for is:

\sum(vect[i]*float(mult[i][1]))

But, I am unable to get that.

For a concrete example:

print(vect)
for i in range(2):
    print(mult[i][1])
lat_alloy = [3]
for i in range(len(m)):
    nvect[i] = vect[i]*float(mult[i][1])
lat_alloy[1] = sum(item[1] for item in nvect)
lat_alloy[2] = sum(item[2] for item in nvect)
lat_alloy[3] = sum(item[3] for item in nvect)
print(lat_alloy)

and I am failing very early with:

[[286.65, 286.65, 286.65], [250.71, 250.71, 406.95]]
20
80
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/site-packages/ptbl/veggards.py", line 68, in entry_text
    nvect[i] = vect[i]*float(mult[i][1])
TypeError: can't multiply sequence by non-int of type 'float'

What I am trying to get is:

[286.65, 286.65, 286.65]*20 
   +       +       +
[250.71, 250.71, 406.95]*80

Kindly help.

Upvotes: 0

Views: 46

Answers (1)

Navidad20
Navidad20

Reputation: 832

Because I had problems with some of the other parts of your code, I changed other parts as well:

# These were my inputs
vect = [[286.65, 286.65, 286.65], [250.71, 250.71, 406.95]]
mult = [[0,20],[0,80]]

lat_alloy = []
for i in range(len(vect)):
    lat_alloy.append([j * float(mult[i][1]) for j in vect[i]])

results = []
for i in range(len(lat_alloy[0])):
    results.append(sum([j[i] for j in lat_alloy]))
print(results)

Or if you wanted some really concise, but unclear code:

lat_alloy = [([j * float(mult[i][1]) for j in vect[i]]) for i in range(len(vect))]
results = [(sum([j[i] for j in lat_alloy])) for i in range(len(lat_alloy[0]))]
print(results)

Both Outputs:

20
80
[25789.8, 25789.8, 38289.0]

Upvotes: 1

Related Questions