fabiomaia
fabiomaia

Reputation: 602

Compute matrix of indices of points whose distance between each other does not exceed some constant

Consider a square matrix D of size nxn which represents pairwise distances between n points, i.e. D(1, 2) is the distance between point 1 and 2 or, generically, D(i, j) is the distance between point i and j.

I want to compute another matrix L of size mx2 of indices (i, j) of the m points whose distance between each other does not exceed some constant w.

For example, given D

octave:1> D = [1 2 3; 4 5 6; 7 8 9]
D =

   1   2   3
   4   5   6
   7   8   9

For w = 4 I want in L the indices (i,j) of points whose distance does not exceed w = 4

octave:2> L = [1 2; 2 2; 3 2; 1 3; 2 3; 3 3]
L =

   1   2
   2   2
   3   2
   1   3
   2   3
   3   3

As a first approximation I have done this fairly naively

D(D > w) = 0;

L = [];
for i = 1:size(D,1)
  for j = 1:size(D,2)
    if D(i, j) != 0
      L = [L; i j];
    end
  end
end

Is there a faster (emphasis on faster) or simpler way to do this? I am not too familiar with MATLAB.

Upvotes: 0

Views: 57

Answers (1)

OmG
OmG

Reputation: 18838

Using find:

D = [1 2 3; 4 5 6; 7 8 9];
w = 4;
[I, J] = find(D <= w);
L = [I J];

Upvotes: 2

Related Questions