问题
I'm trying to define a cubic spline as a function in Mathematica 8
as I've got every P_{i}
(which, of course, are polynomials of degree 3) for each interval [x_{i}, x_{i + 1}], i = 0, ..., n
. What I want to do is to define s
in the interval [x_{0}, x_{n + 1}]
as
. How can I do that as s(x) = P_{i}(x) if x is in [x_{i}, x_{i+1}]
n
varies? I was thinking of Piecewise
but that didn't work.
回答1:
This does precisely what you ask, if I'm not mistaken. It's a bit ugly though. There are better alternatives.
n = 5;
ClearAll[f];
f[x_] = Piecewise[Table[{x^k, (k - 1)/n < x <= k/n}, {k, 0, n}]]
f[1/2]
(* ==> 1/8 *)
If you want to make the result dependent on the current state of the global variable n
(which I wouldn't advocate) thne you can replace the Set
(=) in the definition of f
with SetDelayed
(:=), but this implies re-evaluating the Table
for every call of f
. Not that bad for small values of n, but I don't like it. Results in that case look like this:
n = 2; f[1/2]
n = 5; f[1/2]
(* ==> 1/2
==> 1/8
*)
回答2:
I really don't understand what you are asking for, but going with my best guess, you may find value in this:
p = {func1, func2, func3, func4, func5};
s = If[
1 <= # <= Length@p,
p[[Floor[#]]][#],
"Undefined"
] &;
s /@ {2.4, 1.2, 3.3, 4.8, 1.3, -2.5}
{func2[2.4], func1[1.2], func3[3.3], func4[4.8], func1[1.3], "Undefined"}
I am sorry if this is not helpful.
回答3:
Ivan, I think there are a number of ways to do what you want, more or less contrived, based on your comment to my first answer. Perhaps you are looking for the functionality of Interpolation
most generally. Example:
n = 5;
Table[{k/n, k}, {k, 0, n}]
f = Interpolation[%, InterpolationOrder -> 0];
Plot[f[i], {i, 0, 1}, PlotRange -> All]
来源:https://stackoverflow.com/questions/8545524/is-there-something-like-generalized-piecewise-in-mathematica