Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

search multiple results for multiple conditions

조회 수: 1 (최근 30일)
K VdB
K VdB 2017년 8월 4일
마감: MATLAB Answer Bot 2021년 8월 20일
THE CONTEXT:
I have a set of points in a virtual 2D space. Every point has its own x and y coordinate in space.
P = [1,2 ; 2 5; 4 6; 7 8; ...] % first column are x coordinates and second column are y coordinates
If I want to find the point that is closest to the first one [1,2] I can find the distance between the first point an the other points:
dis = sqrt((P(:,1)-1).^2 + (P(:,2)-2).^2)
dis = [0 ; 3.1623 ; 5 ; 8.4853 ; ...]
if I then search for the second smallest value in 'dis' I know which point is closest to the first point
THE QUESTION:
To generate the closest point for every point I can use a for loop
for i=1:length(P)
dis = sqrt((P(:,1)-P(i,1).^2 + (P(:,2)-P(i,2).^2);
index = secondsmallest(dis) % find index of second smallest value somehow
P_indices(i) = index; % store index in an array'
end
Is there a way to find these indices without using a for loop?
.
Kind regards
Kjartan

답변 (3개)

Star Strider
Star Strider 2017년 8월 4일
I would use the pdist (link) function. You can use ordinary matrix indexing to find the indices of the various values. Also see the sort (link) function, as well as the functions linked in and at the end of the documentation pages.

dpb
dpb 2017년 8월 4일

Jan
Jan 2017년 8월 4일
편집: Jan 2017년 8월 4일
for i=1:length(P)
dis2 = (P(:,1) - P(i,1).^2 + (P(:,2) - P(i,2).^2; % Omit SQRT() to save time
index = secondsmallest(dis2); % find index of second smallest value somehow
P_indices(i) = index; % store index in an array'
end
function k = secondsmallest(x)
[~, k] = min(x);
x(k) = Inf;
[~, k] = min(x);
end
This is faster than sorting the complete vector.
Be sure that P_indices is pre-allocated before the loop.

이 질문은 마감되었습니다.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by