MATLAB: How to compute the ratio of the insection point in each grid on the boundary of a real structure

intersectionMATLAB

In the Cartesian grid, the real structures are pixelized into the staircase approximation. To reduce the staircase error, the effective permittivity is computed, which is weighted by the fraction of the mesh step inside the material 1 or 2 (See the below figure). For instance, the structure is sphere. How I can compute the fraction ratio of four edges in each grid on the boundary of the sphere? Could you please give me some suggestions?
% build Cartesian grid
[Y1,X1]=meshgrid(y_1grid,x_1grid);
% build structure (sphere)
UCC= ((X1+dx/2).^2 + (Y1+dy/2).^2) <= (diam/2.0)^2;
eps_cc=eps(2)*(UCC==1)+eps(1)*(UCC==0);
% find the boundary
[Fx,Fy]=gradient(eps_cc);
boundary=(Fx~=0)|(Fy~=0);
% compute the ratio of intersection point
??
Big Thanks to you

Best Answer

Assuming the boundary has one connexed piece
x=-3:12;
y=-3:10;
[X,Y]=meshgrid(x,y);
cx = 4;
cy = 3;
r = 5;
Z = (X-cx).^2 + (Y-cy).^2 - r^2;
C = contourc(x,y,Z,[0 0]);
Cx = C(1,2:end);
Cy = C(2,2:end);
[Cx; Cy] % fractional crossing is grouped here
close all
hold on
plot(X,Y,'-b');
plot(X',Y','-b');
plot(Cx,Cy,'-r');
plot(cx,cy,'ko');
axis equal