Search code examples
matlabregressioncurve-fittingellipsebest-fit-curve

How to fit an elliptic cone to a set of data?


I have a set of 3d data (300 points) that create a surface which looks like two cones or ellipsoids connected to each other. I want a way to find the equation of a best fit ellipsoid or cone to this dataset. The regression method is not important, the easier it is the better. I basically need a way, a code or a matlab function to calculate the constants of the elliptic equation for these data.


Solution

  • You can also try with fminsearch, but to avoid falling on local minima you will need a good starting point given the amount of coefficients (try to eliminate some of them).

    Here is an example with a 2D ellipse:

    % implicit equation
    fxyc = @(x, y, c_) c_(1)*x.^2 + c_(2).*y.^2 + c_(3)*x.*y + c_(4)*x + c_(5).*y - 1; % free term locked to -1
    
    % solution (ellipse)
    c_ = [1, 2, 1, 0, 0]; % x^2, y^2, x*y, x, y (free term is locked to -1)
    
    [X,Y] = meshgrid(-2:0.01:2);
    figure(1);
    fxy = @(x, y) fxyc(x, y, c_);
    c = contour(X, Y, fxy(X, Y), [0, 0], 'b');
    axis equal;
    grid on;
    xlabel('x');
    ylabel('y');          
    title('solution');          
    
    % we sample the solution to have some data to fit
    N = 100; % samples
    sample = unique(2 + floor((length(c) - 2)*rand(1, N)));
    x = c(1, sample).';
    y = c(2, sample).';
    
    x = x + 5e-2*rand(size(x)); % add some noise
    y = y + 5e-2*rand(size(y));
    
    fc = @(c_) fxyc(x, y, c_); % function in terms of the coefficients
    e = @(c) fc(c).' * fc(c); % squared error function
    
    % we start with a circle
    c0 = [1, 1, 0, 0, 0];
    
    copt = fminsearch(e, c0)
    
    figure(2);
    plot(x, y, 'rx');
    hold on
    fxy = @(x, y) fxyc(x, y, copt);
    contour(X, Y, fxy(X, Y), [0, 0], 'b');
    hold off;
    axis equal;
    grid on;
    legend('data', 'fit');
    xlabel('x');                    %# Add an x label
    ylabel('y');          
    title('fitted solution');
    

    enter image description here