# Doubly indexed sum

I would like to define a doubly indexed sum. Below is what I did:

V=list(var(','.join(['a_%d%d' % (i,n) for i in [0..5] for n in [0..5]])))
sum(a_in*binomial(5,i)*binomial(5,n) for i in [0..5] for n in [0..5])


I get the global name 'a_' is not defined error. I tried this when there is only one index and it works, but doesnt seem to work for double index. Can anyone help me with this?

edit retag close merge delete

Sort by ยป oldest newest most voted

You cannot use directly a_in but must first go through a string "a_{}{}".format(i,n) to generate the variable name and then use the function eval to get the symbolic variable:

sum(eval("a_{}{}".format(i,n))*binomial(5,i)*binomial(5,n) for i in [0..5] for n in [0..5])

more

Thanks very much for your help! it works.

( 2015-05-22 18:26:00 +0200 )edit
1

An alternative is to create the symbolic variables a_* in a 2-dimensional array and to access them as a[i][n] (thereby avoiding the use of eval):

a = [[var("a_{}{}".format(i,n)) for n in [0..5]] for i in [0..5]]
sum(a[i][n]*binomial(5,i)*binomial(5,n) for i in [0..5] for n in [0..5])

( 2015-05-24 11:14:08 +0200 )edit