Can I use ismembertol to find x,y coordinates that are close to each other?
4 views (last 30 days)
Show older comments
I want to compare coordinates from one array to coordinates from another. Can this work since I cannot directly put ordered pairs into a matrix in MATLAB?
0 Comments
Answers (2)
Jon
on 19 Jul 2023
Edited: Jon
on 19 Jul 2023
If I am understanding what you are trying to do correctly I think this would do what you ask
% Define some example coordinates
A = [1.3 2.8
2.5 3.9
6.2 8.7
5.4,4.3];
B = [2.49 3.88
5.39,4.31];
% Define tolerance
tol = 0.02;
% Find points in A that match B
Amatch = A(ismembertol(A,B,tol,'ByRows',true),:)
4 Comments
Jon
on 19 Jul 2023
As @Star Strider suggests, rather than putting tolerances separately on the x and y coordinates, the Euclidean distance from the points in B to the points in A is a good criteria for judging whether they approximately match.
If you have the Statistical and Machine Learning toolbox, then you can use pdist2 for this as described by @Star Strider.
If you don't have the Statistical and Machine Learning toolbox, you could compute the distances and use them as follows
% Define some example coordinate
A = [1.3 2.8
2.5 3.9
6.2 8.7
5.4,4.3];
B = [2.49 3.88
5.39,4.31];
% Define tolerance for matching points
tol = 0.05; % adjust for your needs
% Find distance from each point in B to each point in A
% in a distance matrix, D, with D(i,j) giving distance from ith point in A
% to jth point in B
% Represent 2d points as complex values for easy distance manipulation as
% vectors instead of m by 2 matrices
Ac = A*[1;1i];
Bc = B*[1;1i];
D = abs(Ac - Bc.'); % matrix whose i,j entry give d
% Find matching rows in A corresponding to each row in B based on distance
% tolerance
idx = find(D<=tol); % return linear indices into distance matrix
[r,~] = ind2sub(size(D),idx); % find row in A which matches
% List the matching points
Amatch = A(r,:)
% Or, you could just find the matches based on the closest value without a
% specific tolerance
[~,r] = min(D);
Amatch = A(r,:)
Star Strider
on 19 Jul 2023
The best approach to find (x,y) pairs that are close to each other is probably to use pdist2. You can then compare the distances. The ismember function can then be useful in finding the closest pairs.
Example —
A = randn(10,2)
B = randn(9,2)
[D,I] = pdist2(A,B, 'euclidean','smallest',size(A,1))
Ds = sort(D(:),'ascend');
[~,idx] = ismember(D,Ds(1:10)); % Return Informaton For The Closest 10 Pairs
[r,c] = arrayfun(@(x)find(idx == x), 1:10); % Return Row & Col Indices
DistIdx = table(Ds(1:10),r(:),c(:), 'VariableNames',{'Distance','A Row','B Row'}) % Results Table
Make appropriate changes to get the desired result.
.
0 Comments
See Also
Categories
Find more on Get Started with Statistics and Machine Learning Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!