Find the closest co-ordinates (between to uneven list of cooardinates)

5 views (last 30 days)
I want to select the coordinates in PointinCh1 list which have a coordinates in PointinCh2 list close to them. The code that I am suing at the moment is creating a list called 'closestForPin2toPin1', which is not helpful in finding the indexes in PointinCh1 .
Your help will be appreciated
PointinCh1 =
20 482
19 359
45 438
61 248
90 403
104 95
149 335
148 392
161 73
186 29
188 236
189 319
200 162
208 70
204 198
203 343
214 250
225 307
233 171
238 205
237 245
253 148
264 362
281 34
300 341
306 88
305 203
328 234
326 164
330 20
364 199
424 241
433 314
491 187
PointinCh2 =
99 399
104 95
149 335
148 392
158 82
184 238
190 320
202 343
236 246
263 361
299 342
330 20
493 193
%compute Euclidean distances:
for idis=1: length(PointinCh1)
distances = sqrt(sum(bsxfun(@minus, PointinCh2, PointinCh1(idis,:)).^2,2));
%find the smallest distance and use that as an index into B:
closestForPin2toPin1(idis,:)= PointinCh2(find(distances==min(distances)),:);
end

Accepted Answer

KSSV
KSSV on 7 Mar 2017
Read about inbuilt function knnsearch .
  2 Comments
Peyman Obeidy
Peyman Obeidy on 7 Mar 2017
[n,d]=knnsearch(PointinCh1,PointinCh2,'k',10,'distance','minkowski','p',5); what is next? :)
KSSV
KSSV on 7 Mar 2017
You read the documentation part. knnsearch gives you indices of the points closer to the given points, that's what you wanted.

Sign in to comment.

More Answers (2)

Image Analyst
Image Analyst on 7 Mar 2017
Try pdist2():
PointinCh1 = [
20 482
19 359
45 438
61 248
90 403
104 95
149 335
148 392
161 73
186 29
188 236
189 319
200 162
208 70
204 198
203 343
214 250
225 307
233 171
238 205
237 245
253 148
264 362
281 34
300 341
306 88
305 203
328 234
326 164
330 20
364 199
424 241
433 314
491 187]
PointinCh2 = [...
99 399
104 95
149 335
148 392
158 82
184 238
190 320
202 343
236 246
263 361
299 342
330 20
493 193]
d = pdist2(PointinCh1, PointinCh2)
minDistance = min(d(:))
[row, col] = find(d == minDistance)

Peyman Obeidy
Peyman Obeidy on 7 Mar 2017
Thank you both, I think knnsearch works better, as you see I have 13 points in PointinCh2, so I expect to find them in PointinCh1
  1 Comment
Image Analyst
Image Analyst on 7 Mar 2017
Knowing both, I can't definitively say one is better than the other. They're both just a few lines of code and both will handle finding the indexes closest to each point. They both check the distance of every point to every other point. And they both require the Statistics and Machine Learning Toolbox. So in end they seem pretty equivalent, but I'm glad KSSV mentioned knnsearch() because I did not think of that, and it's a good answer.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!