Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In Mathematica there are different objects like InterpolatingFunction or SparseArray? How can I define a custom data object with special data structure?

Example:

f = Interpolation[{1, 2, 3, 5, 8, 5}];
f // InputForm

returns us

InterpolatingFunction[{{1, 6}}, {4, 3, 0, {6}, {4}, 0, 0, 0, 0, Automatic}, 
{{1, 2, 3, 4, 5, 6}}, {{1}, {2}, {3}, {5}, {8}, {5}}, {Automatic}]

But if one evaluates the above output one gets back

InterpolatingFunction[{{1, 6}}, <>]

I could not find any documentation how to do it for any custom data object that I want to define for my program.

share|improve this question
up vote 20 down vote accepted

Format is what you are looking for: Create a data structure, something like this:

mkMyData[d1_, d2_] := MyData[d1, d2]
GetD1[a_MyData] := a[[1]]
GetD2[a_MyData] := a[[2]]
Format[MyData[d1_, d2_]] := "MyData[<" <> ToString[Length[d1] + Length[d2]] <> ">]"

Call the constructor:

data = mkMyData[Range[5], q]

(* "MyData[<5>]" *)

Call a selector:

GetD1[data]

(* {1, 2, 3, 4, 5} *)

share|improve this answer

As Michael Pilat explained here it is more robust to use MakeBoxes, rather than Format.

Using MakeBoxes:

MakeBoxes[diag[m_?MatrixQ], _] ^:= 
  InterpretationBox[RowBox[{"diag", "[", #, ",", #2, "]"}], diag[m]] & @@
    ToBoxes /@ {Dimensions[m], Diagonal[m]}

Here is a definition for handling Part extraction:

diag[m_?MatrixQ][[part___]] ^:= m[[part]]

Result:

mat = DiagonalMatrix[{1, 2, 3, 4, 5}];

diag[mat]
diag[{5, 5}, {1, 2, 3, 4, 5}]
diag[mat][[2]]
{0, 2, 0, 0, 0}
share|improve this answer
    
Is there a way to handling Apply or Function for your example, ie. such that diag[mat]["Something"] would result specified result? – Karolis Jul 7 at 13:49
1  
@Karolis I think you are looking for (7999)? The formatting rule (with MakeBoxes) should be independent of other definitions so this form should still work, e.g. diag[m_?MatrixQ]["Det"] := Det[m] and then diag[mat]["Det"] evaluates to 120 just as Det[mat] does. – Mr.Wizard Jul 7 at 20:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.