www.gusucode.com > Arduino_Engineering_Kit_Project_Files工具箱matlab程序 > Arduino_Engineering_Kit_Project_Files/DrawingRobot/Solutions/connectSegments.m
function segments = connectSegments(segments) % Copyright 2018 The MathWorks, Inc. % Close any segments that self-intersect (like an "O" or a "P") for ii = 1:length(segments) points = segments{ii}; p1 = points(1,:); pN = points(end,:); % Add any points near p1 to beginning of segment ii nearP1 = isadjacent(p1,points(4:end,:)); %Don't check first 3 points if any(nearP1) idx = find(nearP1,1)+3; points = [points(idx,:); points]; %#ok<*AGROW> end % Add any points near pN to end of segment ii nearPN = isadjacent(pN,points(1:end-3,:)); %Don't check last 3 points if any(nearPN) idx = find(nearPN,1); points = [points; points(idx,:)]; end segments{ii} = points; end % Merge segments with adjacent endpoints for ii = 1:length(segments)-1 jj = ii + 1; % Check all combinations of 2 segments ii and jj while jj <= length(segments) points_i = segments{ii}; points_j = segments{jj}; pi1 = points_i(1,:); piN = points_i(end,:); pj1 = points_j(1,:); pjN = points_j(end,:); % Compare points 1 and N from segments ii and jj if isadjacent(pi1,pj1) segments{ii} = [flipud(points_j); points_i]; segments(jj) = []; elseif isadjacent(pi1,pjN) segments{ii} = [points_j; points_i]; segments(jj) = []; elseif isadjacent(piN,pj1) segments{ii} = [points_i; points_j]; segments(jj) = []; elseif isadjacent(piN,pjN) segments{ii} = [points_i; flipud(points_j)]; segments(jj) = []; end jj = jj + 1; end end end % Subfunction to define if points are adjacent function tf = isadjacent(p1,p2) tf = all(abs(p1-p2) <= [1 1],2); end