This is documentation for Mathematica 3, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.2)
 Documentation / Mathematica / The Mathematica Book / Principles of Mathematica / Transformation Rules and Definitions  /

2.4.5 Making Definitions for Indexed Objects







In many kinds of calculations, you need to set up "arrays" which contain sequences of expressions, each specified by a certain index. One way to implement arrays in Mathematica is by using lists. You can define a list, say a=


x,y,z, ... , then access its elements using a


[[i]], or modify them using a[[i]]=value. This approach has a drawback, however, in that it requires you to fill in all the elements when you first create the list.
Often, it is more convenient to set up arrays in which you can fill in only those elements that you need at a particular time. You can do this by making definitions for expressions such as a[i].

  • This defines a value for a[1].
  • In[1]:= a[1] = 9

    Out[1]=

  • This defines a value for a[2].
  • In[2]:= a[2] = 7

    Out[2]=

  • This shows all the values you have defined for expressions associated with a so far.
  • In[3]:= ?a

    Global`a

    a[1] = 9

    a[2] = 7

  • You can define a value for a[5], even though you have not yet given values to a[3] and a[4].
  • In[4]:= a[5] = 0

    Out[4]=

  • This generates a list of the values of the a[i].
  • In[5]:= Table[a[i], {i, 5}]

    Out[5]=

    You can think of the expression a[i] as being like an "indexed" or "subscripted" variable.


    Manipulating indexed variables.

    When you have an expression of the form a[i], there is no requirement that the "index" i be a number. In fact, Mathematica allows the index to be any expression whatsoever. By using indices that are symbols, you can for example build up simple databases in Mathematica.

  • This defines the "object" area with "index" square to have value 1.
  • In[6]:= area[square] = 1

    Out[6]=

  • This adds another result to the area "database".
  • In[7]:= area[triangle] = 1/2

    Out[7]=

  • Here are the entries in the area database so far.
  • In[8]:= ?area

    Global`area

    area[square] = 1

    area[triangle] = 1/2

  • You can use these definitions wherever you want. You have not yet assigned a value for area[pentagon].
  • In[9]:= 4 area[square] + area[pentagon]

    Out[9]=