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...
Thanks,
Jason
--
Jason Grout
--
To post to this group, send email to sage-support@googlegroups.com
To unsubscribe from this group, send email to
sage-support+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org