MathGroup Archive 2003

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

Search the Archive

Re: Advice on defining a data structure in Mathematica

  • To: mathgroup at
  • Subject: [mg44114] Re: [mg44014] Advice on defining a data structure in Mathematica
  • From: Omega Consulting <info at>
  • Date: Thu, 23 Oct 2003 07:15:08 -0400 (EDT)
  • Sender: owner-wri-mathgroup at

At 04:14 AM 10/17/2003, Mark Coleman wrote:
>I'm an econometrician that has used Mathematica for several years. Now I've
>finally decided to sit down and generalize some of my code to better
>handle time series data. I'd like to get some opinions on good ways to
>define a time series "data structure". Ideally this structure would
>carry all of the important information about the series, e.g, the
>numercial values, the corresponding dates, the frequency, information
>for how to convert the series from one frequency to another (say
>monthly to quarterly), the textual name of the time series (say GDP),
>and some brief descriptive information.
>Obviously this could be structured as a list of lists, but that strikes
>me as not very elegant. I've seen examples of Mathematica code that creates
>objects that remind me of traditional record data structures using up
>values. Is this the preferred approach?

The typical way is to give the type a special head and put the data inside. 
(It doesn't matter how the data is organized as long as it makes sense to you.)

MyType[ ... data ... ]

This way when you write a function you can test for the type by matching 
the head.

function[type_MyType] := ...

Or overload a built-in function with an upvalue

MyType/: a_MyType + b_MyType := ...

And whenever you work with the type don't do things like

data = MyType[...];
value = data[[4]];

Because this depends on how the data is stored in the type (which you may 
decide to change). Instead, create and use constructors and selectors.

data = constructor[...];
value = selector[data];

Then if you decide to change how the data is stored, you only need to 
change the constructors and selectors. And everything else will continue to 

It's also useful to hide the internal data in output. You can do this with 
Format or MakeBoxes.

Format[type_MyType] := "-MyType-"
MakeBoxes[type_MyType, form_] := "-MyType-"

Omega Consulting
"The final answer to your Mathematica needs"

  • Prev by Date: Using multiple reference to the same object
  • Next by Date: LogLogListPlot, LogLinearListPlot- Ticks and TickMarks
  • Previous by thread: Advice on defining a data structure in Mathematica
  • Next by thread: LinearSolve - consumption time for square and rectangular matrices