Mathematicaで関数を定義する

ウォルフラムのMathematica本にあまり詳しく書いていないようなので。まあ、mathematica使いなら誰でも知ってると思いますが。

関数を定義する時にはModule関数を使い、その中に処理を書く。一つ一つの処理の間は;で区切る。また、{ndist, XVec, YVec, ZVec}は局所変数を定義している。


FindCoeff[a_, b_] := Module[
{ndist, XVec, YVec, ZVec},
ndist = NormalDistribution[0, 1];
XVec = Table[x, {x, 1, 10, 0.5}];
ZVec = Table[Random[ndist], {x , 1, 10, 0.5}];
YVec = a + b ZVec ;
data = Transpose[{ XVec , YVec}];
fit = FindFit[data, c + d x, {c, d}, x];
Plot[c + d x /. fit, {x, -1, 11}];
ListPlot[YVec ];
Return[ List[fit, YVec]]]
]
使い方は以下のように。

fcr = FindCoeff[1, 1]