MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Can one define own indexing function/mapping to be used for an Array

I am trying to implement something where it is more natural to use an 
index that starts at 0 instead of the default 1 for vectors and matrices 
as since this will match the problem I am looking at.

If I write


This will return the Head of u. So have to write u[[1]] to get the first 
entry.  I'd like to write u[[0]] to get the first entry.

I thought about using Array:

In[8]:= u = Array[U[#1] & , 4, 0]
Out[8]= {U[0], U[1], U[2], U[3]}

But this does not do much, I still have to write u[[1]] to access U[0]

I could write my own function to implement a 'get' and 'set' operations 
as in:

In[4]:= get[u_, i_] := u[[i + 1]]

In[5]:= get[u, 0]
Out[5]= U[0]

So, everywhere in the code, where I would have liked to write u[[i]], I 
will replace that by get[u,i], and now my i's will match the textbook 
i's since those are implemented using 0-index arrays.

In an OO setting, I could have defined my own "[[ ]]" function on object 
of type Array, then I can write more u[[i]], where now u's own function 
"[[ ]]" will be used.

Other languages also allow one to define an array with different 
starting index than the default.

Is there a way to do something like this for Array at least. For general 
Lists, I think that might not be possible? It will break everything I 
would imagine.

I am looking at this report:

"Data Structures and Efficient Algorithms in Mathematica",

But thought to also ask here, to see if there might be a simple trick to 
do this for Array, by unprotecting it, and changing something? and then 
protecting the definition again, before I try to implement a data struct 
with the help of the above article to do what I want.


  • Prev by Date: Re: Variable number of arguments
  • Next by Date: How to detect 'bad' characters in expressions in the notebook?
  • Previous by thread: Re: How to create a named compound 3D object?
  • Next by thread: Re: Can one define own indexing function/mapping to be used for an Array