% file bezier2.m
%
% ELEC 200 exercise
% plot 2 Bezier curves given control points with C1 continuity

% =======================================
% 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 83
P0=[2 3];
P1=[3 1];
P2=[4 2];
P3=[3 4];
G1 = [P0;
     P1;
     P2;
     P3];
G2 = [3 4;
      2 6;
      5 7;
      5 2];
% 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
 P1=U*B*G1;
 P2=U*B*G2;
 %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(P1(:,1),P1(:,2),'b-'); hold on;
 plot(P2(:,1),P2(:,2),'m-');
 plot(G1(:,1),G1(:,2),'ro');
 plot(G1(:,1),G1(:,2),'g-'); 
 plot(G2(:,1),G2(:,2),'ro');
 plot(G2(:,1),G2(:,2),'g-'); 
 axis equal; hold off;
 
 %plot Bezier blending functions
 %columns of F (notes page 87)
 F = U*B;
 figure(2);
 plot(F); 