intersection of two spheres in matlab

To find the intersection points of two spheres in MATLAB, we can use the equations for the two spheres and solve them simultaneously.

Assuming we have two spheres with centers c1 and c2, and radii r1 and r2, the equations for the two spheres are:

main.m
(x-c1(1))^2 + (y-c1(2))^2 + (z-c1(3))^2 = r1^2
(x-c2(1))^2 + (y-c2(2))^2 + (z-c2(3))^2 = r2^2
94 chars
3 lines

To solve for x, y, and z, we can use MATLAB's fsolve function:

main.m
function [x,y,z] = sphereIntersection(c1,r1,c2,r2)
    fun = @(x) [...
                (x(1)-c1(1))^2 + (x(2)-c1(2))^2 + (x(3)-c1(3))^2 - r1^2;
                (x(1)-c2(1))^2 + (x(2)-c2(2))^2 + (x(3)-c2(3))^2 - r2^2;
               ];
    [sol, fval] = fsolve(fun, [0;0;0]);
    x = sol(1);
    y = sol(2);
    z = sol(3);
end
327 chars
11 lines

Here, fsolve takes in an anonymous function fun that takes in the x vector and returns the differences between the two sphere equations and their respective radii. We then run fsolve with an initial guess of [0;0;0] for the intersection point. The returned sol is the intersection point, and fval is the value of the difference between the two sphere equations at sol, which should be close to zero.

To find all intersection points, we can use fsolve multiple times with different initial guesses.

gistlibby LogSnag