Re: Functions with data hidden in them
- To: mathgroup at smc.vnet.net
- Subject: [mg81863] Re: Functions with data hidden in them
- From: Hannes Kessler <HannesKessler at hushmail.com>
- Date: Fri, 5 Oct 2007 04:50:44 -0400 (EDT)
- References: <fe28v5$muq$1@smc.vnet.net>
Hello Neil,
here is a possible approach:
As an example, define a function of the single argument x. The
function depends on a given matrix m as parameter.
We can write this MyFunc[m_?MatrixQ][x_].
In the considered example, the function MyFunc[m] multiplies x with
the largest eigenvalue of the matrix m.
The function is defined as follows:
In[1]:=
MyFunc[m_?MatrixQ] := MyFunc[m] = Module[{eigenMax},
eigenMax = Max @ N @ Eigenvalues @ m;
Unprotect @ Function;
Format[Times[eigenMax, #] &] :=
MyFuncData[Short[m, 1], eigenMax];
Protect @ Function;
Times[eigenMax, #] &
];
Repeated calculations of the eigenvalues of m are avoided by the
assignment in the assignment
MyFunc[m_?MatrixQ] := MyFunc[m] = Module[{eigenMax}, ...];
Obviously, the maximum eigenvalue has to be calculated only during the
first function call.
Furthermore, Format[Times[eigenMax, #] &] := ... achieves the wanted
formatting of the virtual function returned from the Module.
The virtual function can be applied then to different arguments x over
and over again.
Here are 2 matrices m1 and m2.
In[2]:=
m1 = {{10, 30, 40, 50, 60}, {30, 20, 50, 60, 70}, {40, 50, 30, 70,
80}, {50, 60, 70, 40, 90}, {60, 70, 80, 90, 50}};
m2 = 20 m1;
Here we get the formatted virtual functions for m1 and m2:
In[4]:=
f1 = MyFunc[m1]
f2 = MyFunc[m2]
Out[4]:=
MyFuncData[{{10,30,40,50,60},{30,20,50,60,70},{<<1>>},{50,60,70,40,90},
{60,70,80,90,50}},280.327]
Out[5]:=
MyFuncData[<<1>>,5606.53]
And here, the functions are mapped on the elements of a vector
In[6]:=
f1 /@ {1, 2}
Out[8]:=
{280.327,560.653}
In[7]:=
f2 /@ {1, 2}
Out[7]:=
{5606.53,11213.1}
You may also have a look into the Splines package
c:\Programme\Wolfram Research\Mathematica\6.0\AddOns\Packages\Splines
\Splines.m
Best regards,
Hannes
On 4 Okt., 10:41, Neil Stewart <neil.stew... at warwick.ac.uk> wrote:
> The Interpolation[] function somehow "hides" the data passed to it in the
> InterpolationFunction object that it returns. In the example below, when
> f[1] is evaluated it is using information from the list data, but does not
> have the list data passed to it as parameter.
>
> In[1]:= data = {{1, 1}, {2, 2}, {3, 3}}
>
> In[2]:= f = Interpolation[data]
>
> In[3]:= f[1]
> Out[3]= 1
>
> How can I write my own function that stores data inside itself in the same
> way that Interpolation does? I'm aiming to write a functions that takes a
> number as a parameter and consults a large data set to return a number. I'm
> not sure where to start - any ideas very welcome!
>
> Thanks,
> Neil.