function bezier_curve(Bnodes, nodes_flag, npts, varargin)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% This function computes a Bezier curve given the number of nodes% by the user, and the node coordinates of the defining polygon.% NO derivatives are used at the end points.%% It uses the formulation of Cohen and Riesenfeld, 1982. "General matrix representations for Bezier and B-spline curves".%% P(t) = [T][N][B]'%'% where 0<=t<=1% T = [t^n t^(n-1) ... t 1];% N = conbinatorial(n, j) * cmbinatorial(n, n-i-j) * (-1)^(n-i-j) when 0<=i+j<=n% N = 0.0 otherwise% B = [ B0 B1 B2 ... Bn], where Bi = [xi yi] (1D row array)%% Ex. B:% B = [[1 1]% [2 3]% [4 3]% [3 1]];%% n = number of nodes of the underlining polygon (== size(B,1))% npts = npoints defined by the user for the Bezier curve to pass through.%% It needs the functions: (1) combinatorial.m (as defined by Simone Marras)%% Simone Marras% simone.marras@gmail.com%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%if(strcmp(nodes_flag,"file") || strcmp(nodes_flag,"f"))
B = load(Bnodes);
else
B = Bnodes;
endclear Bnodes;
n = size(B,1) - 1;
%optargin = size(varargin,2);%fprintf('Number of inputs = %d\n', nargin)if(nargin < 3)
npts = n;
end
t = linspace(0,1,npts);
fori = n:-1:0j = n-i;
T(:,j+1) = t.^i;
end%Compute the combinatorial matrix of coefficients (N)fori = 0:n
forj = 0:n
%Compute Nif(i+j >= 0 && i+j <= n)
N(i+1,j+1) = combinatorial(n, j)*combinatorial(n-j, n-i-j)*(-1)^(n-i-j);
else
N(i+1,j+1) = 0.0;
endendend%Compute the Bezier curve coordinates according to its definition: P(t) = [T][N][B]' '%fori = 1:npts
P(i,1:2) = T(i,:)*N*B;
end%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PLOT OUTPUTS:%Simple plotting without names:% plot(P(:,1), P(:,2));% hold on% plot(B(:,1), B(:,2), "-r");%%% The following plotting lines are adapted from the functions written by% Nguyen Quoc Duan and freely available at www.mathworks.com/matlabcentral/fileexchange/12414-bezier-curve%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%clffigure(1);
h=gcf;
% Conecting 6 Bezier points by straight segmentsplot(B(:,1), B(:,2),'-ro',...'LineWidth',1.5,...'MarkerEdgeColor','r',...'MarkerFaceColor',[.49 1 .63],...'MarkerSize',8);
axis equal;
title('Bezier control points (red triangles) \& Bezier curve (blue curve)', "fontsize",21);
hold on;
plot(P(:,1), P(:,2),'-b',...'LineWidth',1.5);
hold on;
% Locate npts given points%for i = 1:npts% node_label = strcat('P', int2str(i));% text(P(i,1),P(i,2),node_label);%end

## BEZIER curves and surfaces, and some basic computer graphics tools