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

"zero_index_in_Mathematica_1.gif"

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

"zero_index_in_Mathematica_2.gif"

"zero_index_in_Mathematica_3.gif"

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.

"zero_index_in_Mathematica_4.gif"

The array u can now be referenced with zero index with the use of "zero_index_in_Mathematica_5.gif" instead of the normal u[[i]]

"zero_index_in_Mathematica_6.gif"

"zero_index_in_Mathematica_7.gif"

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

"zero_index_in_Mathematica_8.gif"

"zero_index_in_Mathematica_9.gif"

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

"zero_index_in_Mathematica_10.gif"

"zero_index_in_Mathematica_11.gif"

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

"zero_index_in_Mathematica_12.gif"

"zero_index_in_Mathematica_13.gif"

"zero_index_in_Mathematica_14.gif"

"zero_index_in_Mathematica_15.gif"

"zero_index_in_Mathematica_16.gif"

"zero_index_in_Mathematica_17.gif"

"zero_index_in_Mathematica_18.gif"

"zero_index_in_Mathematica_19.gif"

"zero_index_in_Mathematica_20.gif"

"zero_index_in_Mathematica_21.gif"

"zero_index_in_Mathematica_22.gif"

"zero_index_in_Mathematica_23.gif"

"zero_index_in_Mathematica_24.gif"

"zero_index_in_Mathematica_25.gif"

"zero_index_in_Mathematica_26.gif"

Also for a matrix (table)

"zero_index_in_Mathematica_27.gif"

"zero_index_in_Mathematica_28.gif"

"zero_index_in_Mathematica_29.gif"

"zero_index_in_Mathematica_30.gif"

"zero_index_in_Mathematica_31.gif"

"zero_index_in_Mathematica_32.gif"

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 "zero_index_in_Mathematica_33.gif" which is much faster, and the code appears more clear as well

"zero_index_in_Mathematica_34.gif"

Less brackets counting and leads to a more clear code.

Spikey Created with Wolfram Mathematica 7.0