Ask Your Question

Doubly indexed sum

asked 2015-05-22 10:53:04 -0500

cihan gravatar image

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 flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2015-05-22 11:16:03 -0500

eric_g gravatar image

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])
edit flag offensive delete link more


Thanks very much for your help! it works.

cihan gravatar imagecihan ( 2015-05-22 11:26:00 -0500 )edit

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])
eric_g gravatar imageeric_g ( 2015-05-24 04:14:08 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2015-05-22 10:53:04 -0500

Seen: 78 times

Last updated: May 22 '15