Puoi provare ad usare la funzione
solve: in due cicli for annidati, crea le funzioni simboliche che definiscono i cerchi e le linee da passare come input alla funzione
solve.
Se il sistema di equazioni composto dall'equazione dell'i-esimo cerchio e della j-esima linea ha soluzioni "reali" la j-esima linea interseca lo i-esimo cerchio.
% Generate some input data
% Number of lines
nr=5;
% Number of circles
nc=3;
% Define start and end points of the lines
x1=randi(5,nr,1)
x2=randi([10 63],nr,1)
y1=randi(5,nr,1)
y2=randi([10 63],nr,1)
% Define the coordinates of the circles ranges
xCenter=randi([0 33],nc,1)
yCenter=randi([0 33],nc,1)
% Define the radius of the circles
r=randi([3 9],nc,1)
% Identify the XLim and YLim of the axes
x_lim=[min(xCenter-r) max(r+xCenter)]
y_lim=[min(yCenter-r) max(r+yCenter)]
% Create the axes
axes
daspect([1 1 1])
xlim(x_lim)
ylim(y_lim)
hold on
grid on
% Define the symbolic variables
syms X Y
vars=[X Y]
% Loop through the circles
for i=1:nc
% Plot the i-th circle
ch(i)=rectangle('position',[xCenter(i)-r(i) yCenter(i)-r(i) r(i)*2 r(i)*2],'curvature',1);
% Loop through the lines
for j=1:nr
% Evaluate the m and k parameters of the line (y=mx+k)
m=(y2(j)-y1(j))/(x2(j)-x1(j));
k=-m*x1(j)+y1(j);
% Plot the j-th line
rh(i,j)=plot([x_lim(1) x_lim(2)],[m*x_lim(1)+k m*x_lim(2)+k]);
% Define the symbolic equatioons of the i-th circle and of the j-th
% line
eqns=[(X-xCenter(i))^2+(Y-yCenter(i))^2-r(i)^2 == 0,m*X-Y+k == 0];
% Call SOLVE to solve the above defined system of equations
[solx, soly] = solve(eqns, vars,'Real', true);
% If the solutions are REAL, the j-th line intersects the i-thcircle
if(~isempty(solx) && ~isempty(soly))
sh(i,j)=plot(double(solx),double(soly),'o','markerfacecolor','r','markeredgecolor','r');
rh(i,j).Color='r';
else
rh(i,j).Color='k';
end
end
% Delete all the line and the intersections points
% (just to clean up the axes)
delete([rh(i,:) sh(i,:)])
end