1
votes

I have an N by 2 matrix called r (N is very large). r is the position of points in 2D. I searched for the best-optimized way of calculating distance between point. I find that dist function is the best on in less time-consuming if one doesn't try to change it to a square matrix. I wonder if I write

D= pdist(r, 'euclidean');

When I need distance between particle i and j, what is the best way to find it using D vector? I do not really any way without using if. I know that I can do it by

if (i < j) 
    D((i–1)*(m–i/2)+j–i)
end

But as N is very large, this is not efficient. Could anyone help me, please?

1
Wherefore do you need it? Using an if test seems appropriate to me in general.m7913d

1 Answers

0
votes

I'm using ii and jj as row and column indices into the hypohetical distance matrix M = squareform(D) of size and N. The result is ind, such that D(ind) equals M(ii,jj).

t = sort([ii, jj]); % temporary variable
ii = t(2); % maximum of ii and jj
jj = t(1); % minimum of ii and jj
t = N-1:-1:1;
ind = sum(t(1:jj-1)) + ii - jj;