Search code examples
matlabcomputational-geometrymatlab-figurematlab-deployment

How do I generate pair of random points in a circle using Matlab?


Let a circle of known radius be plotted in MATLAB.

Assume a pair of random points whose location has to be determined in terms of coordinates (x1,y1) (x2,y2)..(xn,yn). Pairs should be close to each other. For example T1 and R1 should be near.

As shown in figure, there are four random pairs (T1,R1)..(T4,R4). There coordinates need to be determined wrt to center (0,0).

figure

How can I generate this in MATLAB?


Solution

  • (Complete edit after the question was edited).

    To complete this task, I think that you need to combine the different approaches that have been mentioned before your edit:

    • To generate the centers T1,T2,T3,... in the green torus, use the polar coordinates. (Edit: this turned out to be wrong, rejection sampling must also be used here, otherwise, the distribution is not uniform!)
    • To generate the points R1,R2,R3,... in the circle around T1,T2,T3,... but still in the torus, use the rejection sampling.

    With these ingredients, you should be able to do everything you need. Here is the code I wrote:

    d=859.23;
    D=1432.05;
    R=100;
    N=400;
    
    % Generate the angle
    theta = 2*pi*rand(N,1);
    
    % Generate the radius
    r = d + (D-d)*rand(N,1);
    
    % Get the centers of the circles
    Tx = r.*cos(theta);
    Ty = r.*sin(theta);
    
    % Generate the R points
    Rx=zeros(N,1);
    Ry=zeros(N,1);
    for i=1:N
        while true
            % Try
            alpha = 2*pi*rand();
            rr = R*rand();
    
            Rx(i) = Tx(i) + rr*cos(alpha);
            Ry(i) = Ty(i) + rr*sin(alpha);
    
            % Check if in the correct zone
            if ( (Rx(i)*Rx(i) + Ry(i)*Ry(i) > d*d) && (Rx(i)*Rx(i) + Ry(i)*Ry(i) < D*D) )
               break
            end
        end
    end
    
    % Display
    figure(1);
    clf;
    angle=linspace(0,2*pi,1000);
    plot( d*cos(angle), d*sin(angle),'-b');
    hold on;
    plot( D*cos(angle), D*sin(angle),'-b');
    for i=1:N
        plot(Tx(i),Ty(i),'gs');
        plot(Rx(i),Ry(i),'rx');
        plot([Tx(i) Rx(i)],[Ty(i) Ry(i)],'-k');
    end
    hold off;