MATLAB: Getting a user defined boundary for a bunch of randomly distributed line segments

boundary conditionsrandom network

Regards! I have defined a bunch of random line segments within a square boundary but I want to limit it within a rectangle with a curvature. I have tried a very crude and approximate way by invoking periodic boundary conditions but it is not reproducing the desired results at all. The entire code is given below:
q = rectangle ('position' ,[0 0 100 100]' , 'Curvature', [1 0.7] , 'lineWidth' ,3 );
lx = 100;
ly = 100;
v = 400;
x = zeros(1,v);
y = zeros(1,v);
g = zeros(1,v);
m = zeros(1,v);
n = zeros(1,v);
theta = zeros(1,v);
for i=1:v
m(i) = sqrt((lx*rand)^2);
n(i) = sqrt((ly*rand)^2);
theta(i) = 2*pi*rand;
%Randomly distributed segments
x(i) = sqrt((m(i)+10*cos(theta(i)))^2);
y(i) = sqrt((n(i)+10*sin(theta(i)))^2);
%Boundary conditions for square
if x(i) > lx
x(i) = x(i) - lx/4;
elseif x(i) < -lx
x(i) = x(i) + lx/4;
end
if y(i) > ly
y(i) = y(i) - ly/4;
elseif y(i) < -ly
y(i) = y(i) + ly/4;
end
%Circular boundary conditions (approx)
if (x(i) < 20) && (y(i) < 20)
x(i) = x(i)+(10*rand); y(i) = y(i)+(10*rand);
end
if (m(i) < 20) && (n(i) < 20)
m(i) = m(i)+(10*rand); n(i) = n(i)+(10*rand);
end
if (x(i) < 20) && (y(i) > 80)
x(i) = x(i)+(10*rand); y(i) = y(i)-(10*rand);
end
if (m(i) < 20) && (n(i) > 80)
m(i) = m(i)+(10*rand); n(i) = n(i)-(10*rand);
end
if (x(i) > 80) && (y(i) < 20)
x(i) = x(i)-(10*rand); y(i) = y(i)+(10*rand);
end
if (m(i) > 80) && (n(i) < 20)
m(i) = m(i)-(10*rand); n(i) = n(i)+(10*rand);
end
if (x(i) > 80) && (y(i) > 80)
x(i) = x(i)-(10*rand); y(i) = y(i)-(10*rand);
end
if (m(i) > 80) && (n(i) > 80)
m(i) = m(i)-(10*rand); n(i) = n(i)-(10*rand);
end
hold on
plot([x(i); m(i)], [y(i); n(i)], 'color' ,'b', 'linewidth' ,1);
axis equal;
end
What I am getting at best is this:
Kindly help me out!

Best Answer

Rectangle() does not (yet) give the boundary coordinates all the way around, though people have been screaming for it for years. So you'll have to determine those yourself. Then have a loop where you generate line endpoints, determine if the line endpoints are within the polygon, and if they both are, then add/draw that line, then do another loop iteration to try the next pair of endpoints.