Clear Filters
Clear Filters

Creating a loop to find next point in array

3 views (last 30 days)
function [next_point, distance] = find_next_point(current_point, points_to_check, x, y)
distance = compute_distance(current_point, points_to_check, x, y) %find all distances in array
[distance, idx] = min(distance) %find smallest of these distances
next_point = points_to_check(idx)
end
If current_point = [1] and points_to_check = [2 3 4 5 6 7 8 9 10 11 12] how can I turn this code into a for loop so that it determines the smallest distance to the next point (taken from points_to_check) for each iteration?
e.g. after the first iteration current_point = [4] and points_to check = [2 3 5 6 7 8 9 10 11 12] so each iteration the current point is removed from points_to_check and the current_point changes depending on which is the closest point.

Accepted Answer

Kevin Holly
Kevin Holly on 27 Aug 2021
Edited: Kevin Holly on 27 Aug 2021
Edit: I just realized I misread what you wanted. I thought you needed to remove the distance, not current_point.
Assuming index for distance is same as index for points_to_check. Let me know if this works.
function [next_point, distance] = find_next_point(current_point, points_to_check, x, y)
next_point = [];
for i = length(points_to_check):-1:1
distance = compute_distance(current_point, points_to_check, x, y); %find all distances in array
[~, idx] = min(distance); %find smallest of these distances
%save array of answers
next_point = [next_point points_to_check(idx)];
%Update parameters for next run
current_point = points_to_check(idx);
points_to_check(idx) = [];
end
end

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!