How would I write a function that finds the closest point from a list of coordinates?
3 views (last 30 days)
Show older comments
Joshua Rigby
on 2 Apr 2022
Commented: Joshua Rigby
on 2 Apr 2022
I have to write a function that calculates the distance between multiple points and a base site, then finds the closest point to the base site. This is the format I have to follow:
function [chosen_site, d] = select_closest_site( current_site, site_list, x, y )
where x and y are vectors containing the appropriate coordinates for each point, site_list is a vector with the IDs of the points that will be compared, and current_site is the base site that the distances will be calculated from.
Here's an example of how the code should function:
Consider the list of four sites, with locations x = [3, 1, 2, 2] and y = [5, 2, 4, 6]. Given current_site = 4 and site_list = [1, 3], the function should consider which of sites 1 and 3 is closer to site 4, then select site 1 as it is closer. The function should also report the distance to that site, √2:
I also have to call a function that calculates distance which I have already written. This is what I have for that:
function d = compute_distances( x_c, y_c, x, y )
d = sqrt((x_c - x).^2 + (y_c - y).^2);
end
This is what I have written so far to call in the distance function:
d = compute_distances(x(current_site), y(current_site), x, y);
How would I go about continuing past this? I assume I will have to use the min function but I'm struggling to figure out how to format it.
Any help is appreciated.
0 Comments
Accepted Answer
Riccardo Scorretti
on 2 Apr 2022
Hi Joshua, you can try this:
x = [3, 1, 2, 2];
y = [5, 2, 4, 6];
current_site = 4;
site_list = [1, 3];
[chosen_site, d] = select_closest_site( current_site, site_list, x, y)
function [chosen_site, d] = select_closest_site( current_site, site_list, x, y)
xc = x(current_site);
yc = y(current_site);
[d, ind] = min(sqrt((xc-x(site_list)).^2 + (yc-y(site_list)).^2));
chosen_site = site_list(ind);
end
2 Comments
Riccardo Scorretti
on 2 Apr 2022
The key is that min returns two outputs. Matlab manual reads:
[M,I] = min(X) also returns the indices corresponding to the minimum values. The values in I index into the dimension of X that is being operated on. If X contains more than one element with the minimum value, then the index of the first one is returned.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!