Home > atmlab > geodetic > line_sphere_intersect.m

line_sphere_intersect

PURPOSE ^

LINE_SPHERE_INTERSECT returns intersection points of a line and a sphere (or circle)

SYNOPSIS ^

function [y]=line_sphere_intersect(P1,P2,Pc,r)

DESCRIPTION ^

LINE_SPHERE_INTERSECT returns intersection points of a line and a sphere (or circle)

 FORMAT [y]=line_sphere_intersect(P1,P2,Pc,r]

 OUT     y      intersection point(s) y(1,:)=[x1,y1,z1]
                                                        y(2,:)=[x2,y2,z2]
                     where x1,y1,z1 are cartesian coordinates
                     if size(y,1)=1 the line is a tangent to the sphere 
                     if y=nan there is no interception points
 IN        P1    [xa,ya,zc] cartesian coordinates
                     (a point on the line)
             P2    [xb,yb,zb] cartesian coordinates
                     (a point on the line)
             Pc    the circle center [xc,yc,zc]
             r       the circle radius

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

DOWNLOAD ^

line_sphere_intersect.m

SOURCE CODE ^

0001 %LINE_SPHERE_INTERSECT returns intersection points of a line and a sphere (or circle)
0002 %
0003 % FORMAT [y]=line_sphere_intersect(P1,P2,Pc,r]
0004 %
0005 % OUT     y      intersection point(s) y(1,:)=[x1,y1,z1]
0006 %                                                        y(2,:)=[x2,y2,z2]
0007 %                     where x1,y1,z1 are cartesian coordinates
0008 %                     if size(y,1)=1 the line is a tangent to the sphere
0009 %                     if y=nan there is no interception points
0010 % IN        P1    [xa,ya,zc] cartesian coordinates
0011 %                     (a point on the line)
0012 %             P2    [xb,yb,zb] cartesian coordinates
0013 %                     (a point on the line)
0014 %             Pc    the circle center [xc,yc,zc]
0015 %             r       the circle radius
0016 
0017 %History: created by Bengt Rydberg 2011-11-15
0018 
0019 function [y]=line_sphere_intersect(P1,P2,Pc,r)
0020 
0021 x1=P1(1);
0022 y1=P1(2);
0023 z1=P1(3);
0024 x2=P2(1);
0025 y2=P2(2);
0026 z2=P2(3);
0027 x3=Pc(1);
0028 y3=Pc(2);
0029 z3=Pc(3);
0030 
0031 a=(x2 - x1).^2 + (y2 - y1).^2 + (z2 - z1).^2;
0032 b = 2*[ (x2 - x1)*(x1 - x3) + (y2 - y1) *(y1 - y3) + (z2 - z1)* (z1 - z3) ] ;
0033 c = x3^2 + y3^2 + z3^2 + x1^2 + y1^2 + z1^2 - ...
0034      2*[x3*x1 + y3*y1 + z3*z1] - r^2;
0035 
0036 if (b^2-4*a*c)<0
0037  %no intersections
0038  y=nan;
0039 elseif (b^2-4*a*c)==0
0040  %the line is tangent to the sphere
0041  u1=-b/(2*a);
0042  y=P1+u1*(P2-P1);
0043  else
0044  %two intersections
0045  u1=(-b+sqrt(b^2-4*a*c))/(2*a); 
0046  u2=(-b-sqrt(b^2-4*a*c))/(2*a);
0047  y1=P1+u1*(P2-P1);
0048  y2=P1+u2*(P2-P1);
0049  y=[y1;y2];
0050 end
0051

Generated on Mon 15-Sep-2014 13:31:28 by m2html © 2005