I want to build a function of the form
$f(t)= C + \sum_i A_i*Sin(f_i*t+\phi_i)$
Where $(A_i,f_i,\phi_i)$ are amplitudes, frequencies and phases that I have stored in a text file. Here is my attempt:
BuildOscFunction[indata_,freqvals_]:=Module[{i,j,sin,func,t},
func=Mean[indata[[All,2]]];
For[i=1,i<=Length[freqvals],i++,
func+=freqvals[[i,2]]*Sin[freqvals[[i,1]]*t+freqvals[[i,3]]];
];
f[t_]:=func//Evaluate;
Return[f[t]];
];
Here are example snippets of my data set and list of input parameters:
indata[[;;4]]={{0., 1.00105}, {20.0003, 1.00115}, {40.0007, 0.999966}, {60.001,
1.00177}};
freqvals[[;;4]]={{233.362, 0.000802, 3.93604}, {22.0164, 0.000641, 0.277801},
{113.97, 0.00063, 5.8311}, {243.764, 0.000631, 5.94761}}
The Evaluate command only works if t is not a local variable inside Module. What I want is to get a fully written-out function that I can use at will. Something like,
func[t_]:=BuildOscFunction[indata,freqvals];
func[t] = 1.2 + 0.00802Sin[233.362t+3.93] + 0.000641Sin[22.0164t+0.277801]+...etc
func[2]=1.24
EDIT:
Thank you for the several very helpful responses! I ended up finding success using the selected answer using code like this:
BuildOscFunction[f_,A_,phi_]:=Function[t,Total[A*Sin[f*t+phi]]];
ExampleModule[indata_,freqvals_]:=Module[{funcbuild,func},
funcbuild=BuildOscFunction[freqvals[[All,1]],freqvals[[All,2]],freqvals[[All,3]]];
func[t_]:=funcbuild[t];
];
func[t] successfully behaves like a standard function where it can be evaluated, manipulated, plotted, etc. inside of the Module environment.
Return
does not mean the same thing in Mathematica as it does in other languages. Generally, you won't need to use it. To return something from aModule
, just have it be the last entry in theModule
, and don't use a semicolon. That is,Module[{i,j,sin,func,t}, ...; f[t_] := func // Evaluate]
$\endgroup$BuildOscFunction[in_List, fv_List] := Mean[in[[All, 2]]] + #[[2]] Sin[#[[1]] t + #[[3]]] & /@ fv // Total
andBuildOscFunction[indata, freqvals] /. t -> 2
for a single point evaluation. $\endgroup$