# Creating B-splines using a For Loop

I'm very new to Mathematica (as will make itself clear with this question) and I'm trying to create a program that makes b-splines to fit n points. I'm not quite sure how to reference the i-th point in my list of random reals in order to shift the next spline to begin at the next point. Any help is appreciated.

n = 10;
p1[x_] := 1/6*(-x^3 + 3 x^2 - 3 x + 1);
p2[x_] := 1/6*(3 x^3 - 6 x^2 + 4);
p3[x_] := 1/6*(-3 x^3 + 3 x^2 + 3 x + 1);
p4[x_] := 1/6*(x^3);

points = Table[{RandomReal[{1, 10}], RandomReal[{1, 10}]}, {i, 1, n}];

data = {};
For[j = 0, j <= 7, j++,
spline =
p1[x]*points[[i]] + p2[x]*points[[i + 1]] +
p3[x]*points[[i + 2]] + p4[x]*points[[i + 3]];
AppendTo[data, spline];];

ParametricPlot[data, {x, 0, 1}]

• What happens if you change all j's to i (or i to j)? Does that make it work? Nov 10, 2015 at 17:31

You can also use built-in functions for splines. For instance:

pts = RandomReal[{1., 10.}, {10, 2}];
f = BSplineFunction[pts];
Show[Graphics[{Red, Point[pts], Green, Line[pts]}, Axes -> True],
ParametricPlot[f[t], {t, 0, 1}]] It may be that what I've understood about your implementation is wrong (which is: to fix your code change all instances of j to i in the For loop). If this does not fix your problem, please provide more detail in your question about exactly what you are trying to do.

To illustrate a more compact Mathematica-style version:

n = 10;
p1[x_] = 1/6*(-x^3 + 3 x^2 - 3 x + 1);
p2[x_] = 1/6*(3 x^3 - 6 x^2 + 4);
p3[x_] = 1/6*(-3 x^3 + 3 x^2 + 3 x + 1);
p4[x_] = 1/6*(x^3);
points = RandomReal[{1, 10}, {n, 2}];
data = Dot[{p1[x], p2[x], p3[x], p4[x]}, #] & /@ Partition[points, 4, 1];
Show[
Graphics[{Line@points,
MapIndexed[{PointSize[0.01 Sqrt[First@#2]], Point[#1]} &, points]}
, Axes -> True]
, ParametricPlot[data, {x, 0, 1}]] 