Cubic Bezier curve in matlab

Alec Jacobson

December 20, 2013

weblog/

Here's a nasty anonymous function to compute points along a cubic bezier curve.

For example, the formula for a cubic is pretty compact. If you have some parametric samples t and knot points in the rows of P then:

bez = @(t,P) ...
  bsxfun(@times,(1-t).^3,P(1,:)) + ...
  bsxfun(@times,3*(1-t).^2.*t,P(2,:)) + ...
  bsxfun(@times,3*(1-t).^1.*t.^2,P(3,:)) + ...
  bsxfun(@times,t.^3,P(4,:));

builds an Anonymous Function so that X = bez(t,P) gives you points along the curve.

For a concrete example try:

t = linspace(0,1)';
P = [0 0;0.6 0.1;0.9 0.4;1 1];
X = bez(t,P);
plot(X(:,1),X(:,2));
hold on;
plot(P(:,1),P(:,2),'o-r')
hold off;

which displays the curve in blue and the knots in red:

cubic bezier curve