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.png

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.png

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

zero_index_in_Mathematica_6.png

zero_index_in_Mathematica_7.png

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

zero_index_in_Mathematica_8.png

zero_index_in_Mathematica_9.png

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

zero_index_in_Mathematica_10.png

zero_index_in_Mathematica_11.png

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

zero_index_in_Mathematica_12.gif

zero_index_in_Mathematica_13.png

zero_index_in_Mathematica_14.png

zero_index_in_Mathematica_15.png

zero_index_in_Mathematica_16.png

zero_index_in_Mathematica_17.png

zero_index_in_Mathematica_18.png

zero_index_in_Mathematica_19.png

zero_index_in_Mathematica_20.png

zero_index_in_Mathematica_21.png

zero_index_in_Mathematica_22.png

zero_index_in_Mathematica_23.png

zero_index_in_Mathematica_24.png

zero_index_in_Mathematica_25.png

zero_index_in_Mathematica_26.png

Also for a matrix (table)

zero_index_in_Mathematica_27.gif

zero_index_in_Mathematica_28.png

zero_index_in_Mathematica_29.png

zero_index_in_Mathematica_30.png

zero_index_in_Mathematica_31.gif

zero_index_in_Mathematica_32.png

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.png 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.

Created with the Wolfram Language