# choose data points that nears each other and store in different matrix

1 view (last 30 days)
Laura on 17 Jul 2013
I have a matrix A that has dimension n x 2.
A(:,1) is x-values and A(:,2) is y values.
Choose the the pairs that is near each others within certain distance and store in matrix B that has x value in column 1 and y value in column 2.
Example
A= [1 1 ; 2 2 ; 5 5 ; so on]
let say if the distance we want to set is 2
then dist =sqrt((2-1)^2 +(2-1)^2) = sqrt(2) which is less than 2. So first and second pair are close.
store it in B
B= [1 1 ; 2 2; so on ]
Nothe this is example for 3 pairs and I have n- pair.
Thank you

Matt Kindig on 17 Jul 2013
Edited: Matt Kindig on 17 Jul 2013
One (non-loop) way:
[x1,x2]=meshgrid(A(:,1));
[y1,y2]=meshgrid(A(:,2));
D = sqrt((x1-x2).^2+(y1-y2).^2); %distance matrix
setDistance = 2;
[r,c]=find(D <= setDistance); %find which pairs are below setDistance.
B = [r,c]; %set of pairs
B(r==c,:)= []; %eliminate points paired with itself.

Matt Kindig on 17 Jul 2013
@Hao, Then how do you wish to indicate the pairs in B? In your example in the question, it is not clear how the pairs are shown in B--it looks like B just contains all points which have a point within setDistance of it. Is this what you want? Or do you want to show which points are members of each pair? The latter seems much more useful.
If it were me, I'd be B Nx4, such that the points have the form
B = [x1 y1 x2 y2] where (x1,y1) are the coordinates of the first member of the pair, and (x2,y2) are the coordinates of the second member.
@Jan, Of course, this can be optimized for speed--I included the sqrt() to be explicit. In practice, I would actually use bsxfun() or similar to avoid the expensive meshgrid() call as well.
Laura on 18 Jul 2013
I want to calculate the distance between point i to point j that in the distance of 2. Then store that pairs in the matrix B.
A= [1 1 ; 2 2 ; 5 5 ; so on]
let say if the distance we want to set is 2
then dist =sqrt((2-1)^2 +(2-1)^2) = sqrt(2) which is less than 2. So first and second pair are close.
store it in B
B= [1 1 ; 2 2; so on ]
You see that the first pair of coordinate (1 1) and second pair (2 2) are in the distance of 2 so B has to contain (1,1) and (2,2). Then calculate the pair 1 to pair 3 which is obvious that pair 3 is not in the range. Then check pair 1 to n-pair. Then calculate pair 2 to any pair and do to it to n-pair, so on .
Matt Kindig on 18 Jul 2013
Right, but this means that B doesn't indicate any information as to which points are members of which pairs. As it stands now, your B just contains points which are members of a pair which is within 2 units of another point; however, the pair correspondence is not present.
If this is what you wish to do, you can add this line of code to the end:
B = A(unique(B(:)),:);
to get that result.
However, you lose the pair information. Really it depends on what you intend to do with the points in B once you've found them.