FITSPHERE Fit a sphere to 3D points using the least squares approach. SPHERE = fitSphere(PTS) Fits the equation of a sphere in Cartesian coordinates to the N-by-3 array PTS using the least squares approach. The sphere is represented by its center [xc yc zc] and its radius r: SPHERE = [xc yc zc r]. SPHERE = fitSphere(X, Y, Z) Use three vectors X, Y and Z with the length N instead of a the N-by-3 array PTS. [SPHERE, RESIDUALS] = fitSphere(...) Additionally outputs the residuals in the radial direction. Example: center=-100 + 200*rand(1,3); radius = randi([10 100]); [x,y,z]=drawSphere(center, radius); x=x+rand(size(x)); y=y+rand(size(y)); z=z+rand(size(z)); sampleIdx = randi(numel(x),[1,randi([4, numel(x)])]); x=x(sampleIdx); y=y(sampleIdx); z=z(sampleIdx); sphere = fitSphere(x,y,z); figure('color','w'); hold on; axis equal tight; view(3) drawPoint3d(x,y,z) drawSphere(sphere,'FaceAlpha',0.5) See also: createSphere, drawSphere, intersectLineSphere, intersectPlaneSphere Source: Levente Hunyadi - Fitting quadratic curves and surfaces: https://de.mathworks.com/matlabcentral/fileexchange/45356
Package: matgeom