On Sep 24, 2010, at 9:20 AM, Nicholas Kinar wrote: > Hello, > > Suppose that I have an expression such as the one given below: > > M = Indexed('M') > var('A B C') > i,j,n = symbols('i j n', integer = True) > > expr = A*M(1,2)**n + B*M(-2,1)**n + C*M(-1,-1)**n > > Is there a way to iterate through this expression and apply the following > sequence of operations? > > (1) In each term, take the indexed variable M(i,j) and replace it with > another variable in M_i_j_n format. Thus, for expr given above, > > ( M(1,2)**n ) in the first term would be replaced with another non-indexed > variable M_1_2_n > ( M(-2,1)**n) in the second term would be replaced with another non-indexed > variable M_neg2_1_n > ( M(-1,-1)**n) in the third term would be replaced with another non-indexed > variable M_neg1_neg1_n >
There's no need to iterate through the expression to do this. Just use subs, i.e., expr.subs({M(1, 2)**n: Symbol('M_1_2_n'), M(-2, 1)**n: Symbol('M_neg2_1_n'), …}) Of course, if you want to generate the Symbols automatically, that would require you to be a little more clever. > (2) For every replacement, a list (or similar data structure) is created with > the names of the variables [M_1_2_n, M_neg2_1_n, M_neg1_neg1_n]. The list > contains the names of unique variables, such that if the variable name is > already in the list, it is not added. Is it possible to make this a list of > strings? So it sounds like that is what you want to do. I guess you need to combine the expr.atoms(IndexedElement) with str() or .args and some regular expression replacement. Something like '_'.join([str(t) for t in index.args]).replace('-', 'neg'), where index is a M(1, 2, …) element (again a very GOOD reason to make n an element of M and not an exponent; it is much easier to code that way. > > The following sequence of operations can be used to convert an expression > with indexed elements into a format where the ccode() function can then be > used to output the expression in C/C++ form. > > Nicholas Hmm. To me, it seems like ccode() should be able to do this on its own. Maybe you could submit it as a patch to ccode(). Or maybe it really can and neither of us know about it. Øyvind (or anyone)? Aaron Meurer -- You received this message because you are subscribed to the Google Groups "sympy" group. To post to this group, send email to sy...@googlegroups.com. To unsubscribe from this group, send email to sympy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sympy?hl=en.