Using zero based arrays and lists in Mathematica

Written by Nasser M. Abbasi
Updated October 26,2010

This method uses the Notation package to allow one to index an Array, list or a matrix by using a different indexing than the default which starts at 1.

The problem

Sometime there is a need to start the index of an array or a list from zero, as this can be more natural, depending on the problem. 
To do this in Mathematica, all what is needed is to define a notation where the index mapping can occur.  An example is shown below to explain how this was done

The solution: The Notation package is first loaded

Clear["All`*"]
Needs["Notation`"]

The array is defined as normal, choosing to use a zero index for the content as this represents better the problem to solve

sizeOfArray=4;
startingIndex=0;
u = Array[U[#1] & , sizeOfArray, startingIndex]

A notation is made to access the above array from zero to match the definition of its content. A subscript notation is selected in this example as it was found the easiest and most natural, but other notation could have been used.

Notation[(NotationTemplateTag[(Subscript[u, i_])]) ⟺ (NotationTemplateTag[u[[i+1]]])]

The array u can now be referenced with zero index with the use of (Subscript[u, i]) instead of the normal u[[i]]

(Subscript[u, 0])

The loop now appears more mathematically natural as it starts from zero to length-1

Table[(Subscript[u, i]), {i, 0, Length[u] - 1}]

Comparing this to the default case. There is a mismatch in appearance

u[[1]]

This method can be used with a vector (list) as well

len=10;
v=Table[i,{i,0,len-1}];
Notation[(NotationTemplateTag[(Subscript[v, i_])]) ⟺ (NotationTemplateTag[v[[i_+1]]])]
(Subscript[v, 0])

(Subscript[v, 1])

For[i=0,i<Length[v],i++,Print[(Subscript[v, i])]]

Also for a matrix (table)

(mat=Table[i+j,{i,0,2},{j,0,2}])//MatrixForm
Notation[(NotationTemplateTag[(Subscript[mat, i_,j_])]) ⟺ (NotationTemplateTag[mat[[i_+1,j_+1]]])]

(Subscript[mat, 0,0])

{nRows,nCols}=Dimensions[mat];
(Table[(Subscript[mat, i,j]),{i,0,nRows-1},{j,0,nCols-1}])//MatrixForm

Even if the list or table is to be accesses using the default indexing (from 1), it might be useful to consider using this notation as it speeds entering the index. Instead of writing v[[i]], one enters (Subscript[v, i]) which is much faster, and the code appears more clear as well

Notation[(NotationTemplateTag[(Subscript[v, i_])]) ⟺ (NotationTemplateTag[v[[i_]]])]
v=Table[i,{i,5}]

(*compare this *)
For[i=1,i≤Length[v],i++,Print[(Subscript[v, i])]];

(* to this *)
For[i=1,i≤Length[v],i++,Print[v[[i]]]];

Less brackets counting and leads to a more clear code.