Packing Circles inside a Circle - matlab

Given unit circle, and a set of M smaller circles of radius r. Find the maximum radius of the smaller circles that allows them all to fit inside the unit circle without overlap.
I have the following circles packing in polygon example link
I want to change equations that say that all circles are inside the polygon
theta = 2*pi/N; % Angle covered by each side of the polygon
phi = theta*(0:N-1)'; % Direction of the normal to the side of the polygon
polyEq = ( [cos(phi) sin(phi)]*x <= cdist-r );
to equations that say that all circles are inside the circle, but i don't know how. Can somebody help me?
Kind regards.

In your case, there are no "sides of a polygon" so there is no analogue to theta and you'll need to change every place theta is referenced, and all variables that reference theta (like phi).
Something like the following should work. I've just copy-pasted the code from your link, gotten rid of theta and phi, redefined cdist and polyEq, and made it plot a unit circle in the answer instead of a polygon. Please ask if any of these choices are unclear.
M = 19; % number of circles to fit
toms r % radius of circles
x = tom('x', 2, M); % coordinates of circle centers
clear pi % 3.1415...
cdist = 1; % radius of unit circle
%%%%%% equations saying all circles are inside of unit circle
polyEq = (sqrt(x(1,:).^2 + x(2,:).^2) + r <= cdist);
% create a set of equations that say that no circles overlap
circEq = cell(M-1,1);
for i=1:M-1
circEq{i} = ( sqrt(sum((x(:,i+1:end)-repmat(x(:,i),1,M-i)).^2)) >= 2*r );
end
% starting guess
x0 = { r == 0.5*sqrt(1/M), x == 0.3*randn(size(x)) };
% solve the problem, maximizing r
options = struct;
% try multiple starting guesses and choose best result
options.solver = 'multimin';
options.xInit = 30; % number of different starting guesses
solution = ezsolve(-r,{polyEq,circEq},x0,options);
% plot result
x_vals = (0:100)./100;
plot(sqrt(1 - x_vals.^2),'-') % top of unit circle
plot(-1.*sqrt(1 - x_vals.^2),'-') % bottom of unit circle
axis image
hold on
alpha = linspace(0,2*pi,100);
cx = solution.r*cos(alpha);
cy = solution.r*sin(alpha);
for i=1:M
plot(solution.x(1,i)+cx,solution.x(2,i)+cy) % circle number i
end
hold off
title(['Maximum radius = ' num2str(solution.r)]);

Related

How calculate the distance of all point inside a square?

I Have an issue to create some geometries inside a phantom with Filed II framework. I did create a circle, but now I have problem to create a square inside the phantom.
It is the following code to produce it in Matlab. The line of code that produce inside, is my issue. For the circle, I did calculate the distance of two points inside the circle and when it is less than the radius of the circle, they are inside the circle. But I have problem for triangle or square.
Phantom.x_size = 50/1000; % Width of phantom [mm]
Phantom.y_size = 10/1000; % Transverse width of phantom [mm]
Phantom.z_size = 60/1000; % Height of phantom [mm]
Phantom.z_start = 30/1000; % Start of phantom surface [mm];
N = Calculate_number_of_scatterers(Phantom);
N = 1000*ceil(N/1000);
% Create the general scatterers
x = (rand (N,1)-0.5)*Phantom.x_size;
y = (rand (N,1)-0.5)*Phantom.y_size;
z = rand (N,1)*Phantom.z_size + Phantom.z_start;
% Generate the amplitudes with a Gaussian distribution
amplitudes = randn(N,1);
%Make the cyst
r = 8/2/1000; %radius of cyst[mm]
xc = 10/1000; %place of the cyst
zc = 40/1000 + Phantom.z_start;
% [in,out] = inpolygon(xc,zc,x,z);
inside = ( ((x-xc).^2 + (z-zc).^2) < r^2); % scatteres inside the cyst
amplitudes = amplitudes .* (1-inside); % amplitude of the scatteres inside the cyst
Phantom.positions = [x y z];
Phantom.amplitudes = amplitudes;
figure;
plot3(Phantom.positions(:,1), Phantom.positions(:,3),Phantom.amplitudes,'.')

Divide Mesh grid by a bisector, MATLAB

I have a piecewise function, where domain changes for each case. The function is as follows:
For
(x,y)greater than Divider v= f(x,y) (A1)
(x,y)less than Divider v = g(x,y) (A2)
The location of the divider changes with tilt angle of the rectangle given in figures 1 and 2.Figure 1 & 2 The divider will always be a bisector of the rectangle. For example, the divider makes an angle (alpha + 90) with the horizontal.
If the rectangle makes an angle 0, it's easy to implement above functions as I can create meshgrid from
x =B to C & y = A to D for A1
x =A to B & y = A to D for A2
However, when the angles for the rectangle are different, I can't figure out how to create the mesh to calculate the function v using the algorithm A1 and A2 above.
I was thinking of using some inequality and using the equation of the line (as I have the co-ordinates for the center of the rectangle and the angle of tilt). But, I can't seem to think of a way to do it for all angles (for example , slope of pi/2 as in the first figure, yields infinity). Even if I do create some kind of inequality, I can't create a mesh.
1Please help me with this problem. I have wasted a lot of time on this. It seems to be out of my reach
%% Constants
Angle1=0;
Angle1=Angle1.*pi./180;
rect_center=0; % in m
rect_length=5; % in m
rect_width=1; % in m
rect_strength=1.8401e-06;
Angle2=0;
Angle2 =Angle2.*pi./180;
%% This code calculates the outer coordinates of the rectangle by using the central point
% the following code calculates the vertices
vertexA=rect_center+(-rect_width./2.*exp(1i.*1.5708)-rect_length./2).*exp(1i.*Angle2);
vertexA=[vertexA,vertexA+2.*(rect_width./2.*exp(1i.*1.5708)).*exp(1i.*Angle2)];
vertexB=rect_center+(-rect_width./2.*exp(1i.*1.5708)+rect_length./2).*exp(1i.*Angle2);
vertexB=[vertexB,vertexB+2.*(rect_width./2.*exp(1i.*1.5708)).*exp(1i.*Angle2)];
za1=vertexA(1:numel(vertexA)/2);
za2=vertexA(1+numel(vertexA)/2:numel(vertexA));
zb1=vertexB(1:numel(vertexB)/2);
zb2=vertexB(1+numel(vertexB)/2:numel(vertexB));
arg1=exp(-1i.*Angle2);
%% This Section makes the two equations necessary for making the graphs
syms var_z
% Equation 1
Eqn1(var_z)=1.5844e-07.*exp(-1i.*Angle1).*var_z./9.8692e-13;
% subparts of the Equation 2
A = 1.0133e+12.*(-1i.*rect_strength.*exp(-1i*Angle2)./(2*pi.*rect_length.*rect_width*0.2));
ZA1 = var_z+za1-2*rect_center;
ZA2 = var_z+za2-2*rect_center;
ZB1 = var_z+zb1-2*rect_center;
ZB2 = var_z+zb2-2*rect_center;
ZAA2 = log(abs(ZA2)) + 1i*mod(angle(ZA2),2*pi);
ZAA1 = log(abs(ZA1)) + 1i*mod(angle(ZA1),2*pi);
ZBB1 = log(abs(ZB1)) + 1i*mod(angle(ZB1),2*pi);
ZBB2 = log(abs(ZB2)) + 1i*mod(angle(ZB2),2*pi);
%Equation 2 ; this is used for the left side of the center
Eqn2= A*(ZA2*(log(ZA2)-1)-(ZA1*(log(ZA1)-1))+(ZB1*(log(ZB1)-1))-(ZB2*(log(ZB2)-1)));
%Equation 3 ; this is used for the right side of the center
Eqn3 = A.*(ZA2*(ZAA2-1)-(ZA1*(ZAA1-1))+(ZB1*(ZBB1-1))-(ZB2*(ZBB2-1)));
%Equation 4 :Add Equation 2 and Equation 1; this is used for the left side of the center
Eqn4 = matlabFunction(Eqn1+Eqn2,'vars',var_z);
%Equation 5: Add Equation 3 and Equation 1; this is used for the right side of the center
Eqn5 = matlabFunction(Eqn1+Eqn3,'vars',var_z);
%% Prepare for making the plots
minx=-10; %min x coordinate
maxx=10; %max x coordinate
nr_x=1000; %nr x points
miny=-10; %min y coordinate
maxy=10; %max y coordinate
nr_y=1000; %nr y points
%This vector starts from left corner (minx) to the middle of the plot surface,
%The middle of the plot surface lies at the center of the rectange
%created earlier
xvec1=minx:(rect_center-minx)/(0.5*nr_x-1):rect_center;
%This vector starts from middle to the right corner (maxx) of the plot surface,
%The middle of the plot surface lies at the center of the rectange
%created earlier
xvec2=rect_center:(maxx-rect_center)/(0.5*nr_x-1):maxx;
%the y vectors start from miny to maxy
yvec1=miny:(maxy-miny)/(nr_y-1):maxy;
yvec2=miny:(maxy-miny)/(nr_y-1):maxy;
% create mesh from above vectors
[x1,y1]=meshgrid(xvec1,yvec1);
[x2,y2]=meshgrid(xvec2,yvec2);
z1=x1+1i*y1;
z2=x2+1i*y2;
% Calculate the above function using equation 4 and equation 5 using the mesh created above
r1 = -real(Eqn5(z1));
r2 = -real(Eqn4(z2));
%Combine the calculated functions
Result = [r1 r2];
%Combine the grids
x = [x1 x2];
y = [y1 y2];
% plot contours
[c,h]=contourf(x,y,Result(:,:,1),50,'LineWidth',1);
% plot the outerboundary of the rectangle
line_x=real([vertexA;vertexB]);
line_y=imag([vertexA;vertexB]);
line(line_x,line_y,'color','r','linestyle',':','linewidth',5)
The final Figure is supposed to look like this.Final Expected Figure.
I'm not sure which angle defines the dividing line so I assume it's Angle1. It looks like logical indexing is the way to go here. Instead of creating two separate mesh grids we simply create the entire mesh grid then partition it into two sets and operate on each independently.
%% Prepare for making the plots
minx=-10; %min x coordinate
maxx=10; %max x coordinate
nr_x=1000; %nr x points
miny=-10; %min y coordinate
maxy=10; %max y coordinate
nr_y=1000; %nr y points
% create full mesh grid
xvec=linspace(minx,maxx,nr_x);
yvec=linspace(miny,maxy,nr_y);
[x,y]=meshgrid(xvec,yvec);
% Partition mesh based on divider line
% Assumes the line passes through (ox,oy) with normal vector defined by Angle1
ox = rect_center;
oy = rect_center;
a = cos(Angle1);
b = sin(Angle1);
c = -(a*ox + b*oy);
% use logical indexing to opperate on the appropriate parts of the mesh
idx1 = a*x + b*y + c < 0;
idx2 = ~idx1;
z = zeros(size(x));
z(idx1) = x(idx1) + 1i*y(idx1);
z(idx2) = x(idx2) + 1i*y(idx2);
% Calculate the above function using equation 4 and equation 5
% using the mesh created above
Result = zeros(size(z));
Result(idx1) = -real(Eqn5(z(idx1)));
Result(idx2) = -real(Eqn4(z(idx2)));
For example with Angle1 = 45 and Angle2 = 45 we get the following indexing
>> contourf(x,y,idx1);
>> line(line_x,line_y,'color','r','linestyle',':','linewidth',5);
where the yellow region uses Eqn5 and the blue region uses Eqn4. This agrees with the example you posted but I don't know what the resulting contour map for other cases is supposed to look like.
Hope this helps.

Axillary curve line for a path in Matlab

There is a noisy image as fig a. by reducing image noise finally a smoothspline could fit to the dots as shown in fig b. now it's desire to find two axillary lines both side of the original line like offset (in this case it's better to say outline). how can these lines(yellow and green) position be found?
if there is a simple straight line it would be easy but here is spline.
any idea would be appreciated.
I think this is what you wanted:
% generate random curve
xy = randi(5,[2,3]);
t = 1:3;
tq = linspace(1,3,100);
xyq = interp1(t',xy',tq','spline');
xx = xyq(:,1);
yy = xyq(:,2);
% get curve's approx. angle in each point
theta = atan2(xyq(2:end,2) - xyq(1:end-1,2),xyq(2:end,1) - xyq(1:end-1,1));
theta(end+1) = theta(end);
% add or subtract 90 degrees to get downward or upward normal angle
tp1 = theta + pi/2;
tp2 = theta - pi/2;
% distance from original curve
d = 0.1;
% compute x-y additions
[xa1,ya1] = pol2cart(tp1,d);
[xa2,ya2] = pol2cart(tp2,d);
% plot curve and its axillary lines
plot(xx,yy,'g')
hold on
plot(xyq(:,1) + xa1,xyq(:,2) + ya1,'b')
plot(xyq(:,1) + xa2,xyq(:,2) + ya2,'r')
legend('orig.','axil._1','axil._2');
and you get this:

Flow field around cylinder in Matlab

I'm pretty new to different plots in Matlab and I'm trying to write a code that will show the flow field around a cylinder in Matlab. I'm at the very start and first of all I want to just make the circle in a rectangular domain (cylinder should not be right in the middle of the field).
So far, I have this set up but I want to know if it's possible to make the cylinder look more circular and less like an oval, especially because the domain is a rectangle and not a square. The points on the circle are correct but I want it to look better. Any tips on this? The code I have at the moment is:
U_i = 20; % Ambient velocity
a = 4; % cylinder radius
c = -a*5; % starting coordinate (x)
b = a*10; % ending coordinate (x)
d = -60; % starting coordinate (y)
e = 60; % ending coordinate (y)
n = a*50; % number of intervals (step size in grid)
[x,y] = meshgrid([c:(b-c)/n:b],[d:(e-d)/n:e]');
for i = 1:length(x)
for k = 1:length(x);
f = sqrt(x(i,k).^2 + y(i,k).^2);
if f < a
x(i,k) = 0;
y(i,k) = 0;
end
end
end
% Definition of polar variables
r = sqrt(x.^2+y.^2);
theta = atan2(y,x);
%% Creation of Streamline function
z = U_i.*r.*(1-a^2./r.^2).*sin(theta);%- G*log(r)/(2*pi);
%% Creation of Figure
m = 100;
s = ones(1,m+1)*a;
t = [0:2*pi/m:2*pi];
%% Streamline plot
contour(x,y,z,50);
hold on
polar(t,s,'-k');
% axis square
title('Stream Lines');
grid off

Intersection points of two circles in MATLAB

I need to find out the intersecting points of two circles. I have the center points and the radius of each circle. I need to do it in MATLAB. Any help will be appreciated.
Assume a triangle ABC, where A and B are the centers of the circle, and C is one or the other intersection point. a, b, and c are the sides opposite the corresponding corners. alpha, beta, and gamma are the angles associated with A, B, and C, respectively.
Then, b^2+c^2 - 2*bccos(alpha) = a^2. Knowing alpha (or its cosine), you can find the location of C.
A = [0 0]; %# center of the first circle
B = [1 0]; %# center of the second circle
a = 0.7; %# radius of the SECOND circle
b = 0.9; %# radius of the FIRST circle
c = norm(A-B); %# distance between circles
cosAlpha = (b^2+c^2-a^2)/(2*b*c);
u_AB = (B - A)/c; %# unit vector from first to second center
pu_AB = [u_AB(2), -u_AB(1)]; %# perpendicular vector to unit vector
%# use the cosine of alpha to calculate the length of the
%# vector along and perpendicular to AB that leads to the
%# intersection point
intersect_1 = A + u_AB * (b*cosAlpha) + pu_AB * (b*sqrt(1-cosAlpha^2));
intersect_2 = A + u_AB * (b*cosAlpha) - pu_AB * (b*sqrt(1-cosAlpha^2));
intersect_1 =
0.66 -0.61188
intersect_2 =
0.66 0.61188
Find the equations of the circles. Make sure to account for the negative of the square root or else you will just have a semi circle.
Set the equations of the two circles equal to eachother.
Here is a simple code using two File Exchange submissions: first - to draw circles, second - to find intersections (links below).
clf
N=30; % circle resolution as the number of points
hold on
% draw 1st circle at (0,0) radius 5 and get X and Y data
H1=circle([0 0],5,N);
X1=get(H1,'XData');
Y1=get(H1,'YData');
% draw 2nd circle at (2,5) radius 3 and get X and Y data
H2=circle([2 5],3,N);
X2=get(H2,'XData');
Y2=get(H2,'YData');
% find intersection points
[x,y]=intersections(X1,Y1,X2,Y2,0);
% and plot them as red o's
plot(x,y,'ro')
hold off
axis equal
CIRCLE
Fast and Robust Curve Intersections
Function CIRCCIRC does this for you.
[xout,yout] = circcirc(x1,y1,r1,x2,y2,r2)
This will give you the two intersection points.
http://www.mathworks.nl/help/map/ref/circcirc.html
I am pasting Roger Stafford's answer here. (See link) This also prints if there is no intersection between circles. I think you can figure it the geometrical relations in the code.
% P1 and P2 are column vectors r1 and r2 are their respective radius.
% P1 = [x1;y1]; P2 = [x2;y2];
d2 = sum((P2-P1).^2);
P0 = (P1+P2)/2+(r1^2-r2^2)/d2/2*(P2-P1);
t = ((r1+r2)^2-d2)*(d2-(r2-r1)^2);
if t <= 0
fprintf('The circles don''t intersect.\n')
else
T = sqrt(t)/d2/2*[0 -1;1 0]*(P2-P1);
Pa = P0 + T; % Pa and Pb are circles' intersection points
Pb = P0 - T;
end
Pint = [Pa, Pb];