function [xo,yo] = intsecpl(xv,yv,xl,yl,trace) % INTSECPL Intersection of a polygon and a line. % [XI,YI] = INTSECPL(XV,YV,XL,YL) calculates % intersections XI, YI of a polygon with vertices XV, % YV and a line specified by pairs of end coordinates % XL = [XL0 XL1], YL = [YL0 YL1]. Line is assumed to % continue beyond the range of end points. % INTSECPL(XV,YV,[A B]) uses another specification for % a line: Y = A*X+B. % % If a line does not intersect polygon, returns empty % XI, YI. % For convex polygon maximum number of intersections is % 2, for non-convex polygons multiple intersections are % possible. % % INTSECPL(XV,YV,XL,YL) by itself or % [XI,YI] = INTSECPL(XV,YV,XL,YL,1) plots polygon, % a line segment and intersection segment(s) % (part(s) of the same line inside the polygon). % Copyright (c) 1995 by Kirill K. Pankratov, % kirill@plume.mit.edu. % 06/25/95, 08/27/95, 09/27/95 % Calls ISCROSS, INTSECL programs. % Defaults and parameters ................................. tol = 1e-14; % Tolerance marg = tol; % Margins for polygon frame is_ab = 0; % Default A*X+B mode % Handle input ............................................ if nargin==0, help intsecpl, return, end if nargin < 3 error(' Not enough input arguments') end if nargin<5, trace = 0; end if nargin==4 % Check if 4-th arg is trace if max(size(yl))==1, trace = yl; is_ab = 1; end end if nargin==3, is_ab = 1; end trace = trace | nargin<2; if length(xv)~=length(yv) error(' Vectors X, Y must have the same size') end % Auxillary ........... xv = [xv(:); xv(1)]; yv = [yv(:); yv(1)]; ii = find(abs(diff(xv))1 & 0 % Do not execute xx = [xo yo]; yy = diff(xx)'; ii = [1 find(any(abs(yy)>tol))+1]; xo = xx(ii,1); yo = xx(ii,2); oi = ones(size(xo)); end % Plotting ................................................ if trace oi(3:2:length(oi)) = oi(3:2:length(oi))+1; oi = cumsum(oi); len = max(oi); xp = nan*ones(len,1); yp = xp; xp(oi) = xo; yp(oi) = yo; % Intersection with polygon frame [xl,yl] = intsecpl(lim([1 2 2 1]),lim([3 3 4 4]),xl,yl); plot(xv,yv,xl,yl,xp,yp) % Plotting itself end