Search code examples
matlabplotoctave

Plot Bezier Curve in Octave


I'm trying to plot Bezier Curves in Octave. A Bezier curve is defined by a number of control points, for example:

image

I'm trying to plot something like this. I found out about a function: drawBezierCurve but the function needs four control points and I need to plot a a Bezier curve with just three points. The control points are: a(1,2), b(4,-1), c(8,6). Any ideas?


Solution

  • Take the lines ab and bc:

    a = [1 2];
    b = [4 -1];
    c = [8 6];
    

    ab and ac

    Create n equidistant points on them:

    npoints = 10;
    line1 = linspace(a, b, npoints);
    line2 = linspace(b, c, npoints);
    

    n points

    For the kth point on the Bézier curve, take k / n parts from first line and (n - k) / n parts from the second line.

    weights = linspace(1, 0, npoints);
    curve = line1 .* weights + line2 .* (1 - weights);
    

    points on bezier curve

    Connect the obtained points to draw the curve:

    plot(curve(1, :), curve(2, :))
    

    bezier curve


    The complete code:

    a = [1 2];
    b = [4 -1];
    c = [8 6];
    
    npoints = 10; % modify this
    line1 = linspace(a, b, npoints);
    line2 = linspace(b, c, npoints);
    weights = linspace(1, 0, npoints);
    
    curve = line1 .* weights + line2 .* (1 - weights);
    plot(curve(1, :), curve(2, :))
    

    Additional code to draw the figures in this answer:

    fig = figure;
    hold on
    
    % figure 1
    plot([a(1) b(1)], [a(2) b(2)])
    plot([b(1) c(1)], [b(2) c(2)])
    
    % figure 2
    plot(line1(1, :), line1(2, :), 'ok')
    plot(line2(1, :), line2(2, :), 'or')
    
    % figure 3
    plot([line1(1,:); line2(1, :)], [line1(2, :); line2(2, :)], 'm--')
    
    plot(curve(1, :), curve(2, :), 'oc')
    
    % figure 4
    plot(curve(1, :), curve(2, :), 'b', 'linewidth', 2)