On Jul 4, 8:05 pm, Jason Grout <[email protected]> wrote: > This question has come up often enough that I thought posting a short > snippet here might be useful. The question is: how do I automatically > generate variables based on indices (e.g., a[0], a[1], etc. being > variables). Here is one way: > > class VariableGenerator(object): > def __init__(self, prefix): > self.__prefix = prefix > > @cached_method > def __getitem__(self, key): > return SR.var("%s%s"%(self.__prefix,key)) > > Now just specify a prefix, and then you can index to your heart's > content to generate variables. > > a=VariableGenerator('a') # some people may like 'a_' as the prefix > a[0], a[1], a[2] # all variables > > Of course, this can easily be extended to using function call syntax: > a(0), or to using multiple indices: a[1,3]. Indeed, you can let your > imagination run wild and even do things like return full symbolic > matrices or vectors with slices: a[0:5, 0:5]. > > Perhaps this is useful enough to be in Sage instead of just a snippet > here too... >
Uh, yeah. With the proviso that the usual answer to the question should also be available, so that if people want a1, a2, a3, a4 instead of a[1],a[2],a[3],a[4] that is an option too. I was wondering about how hard it would be to make the former easily available a few weeks ago, but didn't follow through. See http://trac.sagemath.org/sage_trac/ticket/11576 for adding this. -- To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/sage-support URL: http://www.sagemath.org
