Search This Blog

Thursday, April 11, 2013

How to generate random cartesian coordinates given distance constraint in Matlab


I need to generate N random coordinates for a 2D plane. The distance between any two points are given (number of distance is N(N - 1) / 2). For example, say I need to generate 3 points i.e. A, B, C. I have the distance between pair of them i.e. distAB, distAC and distBC.
Is there any built-in function in MATLAB that can do this? Basically, I'm looking for something that is the reverse of pdist() function.
My initial idea was to choose a point (say A is the origin). Then, I can randomly find B and C being on two different circles with radii distAB and distAC. But then the distance between B and C might not satisfy distBC and I'm not sure how to proceed if this happens. And I think this approach will get very complicated if N is a large number.






Elaborating on Ansaris answer I produced the following. It assumes a valid distance matrix provided, calculates positions in 2D based on cmdscale, does a random rotation (random translation could be added also), and visualizes the results:
%Distance matrix
D = [0 2 3; ...
     2 0 4; ...
     3 4 0];

%Generate point coordinates based on distance matrix
Y = cmdscale(D);

[nPoints dim] = size(Y);

%Add random rotation
randTheta = 2*pi*rand(1);
Rot = [cos(randTheta) -sin(randTheta); sin(randTheta) cos(randTheta) ];
Y = Y*Rot;

%Visualization
figure(1);clf;
plot(Y(:,1),Y(:,2),'.','markersize',20)
hold on;t=0:.01:2*pi;
for r = 1 : nPoints - 1 
    for c = r+1 : nPoints
        plot(Y(r,1)+D(r,c)*sin(t),Y(r,2)+D(r,c)*cos(t));
        plot(Y(c,1)+D(r,c)*sin(t),Y(c,2)+D(r,c)*cos(t));
    end
end
enter image description here

No comments:

Post a Comment

Thank you