% file bezier.m
%
% ENGR 150 exercise
% plot Bezier curve given control points

% =======================================
% MATLAB HELP
% to learn more about Matlab, type 'intro'
% (without quotes) at the command prompt
% also type 'demo' for more complete intro
% for help on any function, type 'helpwin functionname'
% for help on syntax:
% type 'helpwin punct' 'helpwin ops'  'helpwin arith'
% 'helpwin colon'
% for web-based help, type 'helpdesk'
% keyword search, type 'lookfor keyword'
% type variable names to get their values
% =========================================

% following lecture notes page 87
% plot Bezier curve
% inputs: control points P0, P1, P2, P3 
% output: Bezier curve

% enter inputs
% notes page 84 problem 1
%P0=[3 3];
%P1=[17 6];
%P2=[7 9];
%P3=[20 12];
% notes page 83
P0=[0 0];
P1=[1 1];
P2=[2 1];
P3=[3 0];
G = [P0;
     P1;
     P2;
     P3];

% to plot curve, need values of u from 0 to 1
% thus make a vector of N points, where e.g. N=100
N=100;
% u = column vector [1 2 3 .... N]'/N
u=(1:N)'/N;

  U = [u.^3 u.^2 u.^1 u.^0]; 
% U = N by 4 matrix with 4 column vectors 
% u.^2 means each element of 
% the column vector u is squared (help punct)
% ones(N,1) is a matrix of 1's with N rows, 1 column
% can also write 
% U = [u.^3 u.^2 u ones(N,1)];

% Bezier coefficient matrix B_k,n 
% for 4 control points (n=3)
B=[-1  3 -3  1;
    3 -6  3  0;
   -3  3  0  0;
    1  0  0  0];
 
 % find Bezier curve using notes page 87
 P=U*B*G;
 
 %P = N by 2 matrix of N points (x,y) on Bezier curve
 %G = N by 2 matrix of 4 control points (x.y)
 
%P(:,1) is column 1 of P (all x values)
%P(:,2) is column 2 of P (all y values)

% plot Bezier curve, control points and defining polygon
 figure(1);
 plot(P(:,1),P(:,2),'b-'); hold on;
 plot(G(:,1),G(:,2),'ro');
 plot(G(:,1),G(:,2),'g-'); axis equal; hold off;
 
 %plot Bezier blending functions
 %columns of F (notes page 87)
 F = U*B;
 figure(2);
 plot(F); 