Filter löschen
Filter löschen

Calculating euclidean distances in a matrix

2 Ansichten (letzte 30 Tage)
Andrea Sbaragli
Andrea Sbaragli am 16 Dez. 2020
Kommentiert: Image Analyst am 16 Dez. 2020
I have to a matrix n x 2 in which each row represent a point in a Cartesian space in X and Y. The distance I have to calculate is between a row and its follower so at the end I have an array (n-1) x 1. I ve coded a simply function but since n = 50 000 it takes a lot of time to compute. How to speed up the entire process?
That s my function:
function [Dist] = Distances(A)
n = length(A)
Dist = (n -1);
for i=1:n
if i == n
break
end
Dist(i,1)= sqrt((A(i+1,1)- A(i,1))^2 + (A(i+1,2)- A(i,2))^2)
i= i+1
end

Antworten (2)

KSSV
KSSV am 16 Dez. 2020
Bearbeitet: KSSV am 16 Dez. 2020
% demo data
n = 100 ;
A = rand(n,2) ;
dA = diff(A) ;
d = sqrt(sum(dA.^2,2)) ;
  1 Kommentar
Image Analyst
Image Analyst am 16 Dez. 2020
This is what I'd do too. It's fast:
tic
n = 50000; % fifty thousand
xy = rand(n,2);
dxy = diff(xy);
d = sqrt(sum(dxy.^2,2));
toc
On my computer it takes 0.003 seconds for 50,000 rows.

Melden Sie sich an, um zu kommentieren.


Star Strider
Star Strider am 16 Dez. 2020
Use the pdist function, then squareform.
Example —
x = randi(99, 5, 2); % Create Matrix
d = pdist(x);
m = squareform(d);
The information you want are in the upper and lower diagonals of ‘m’, so:
Result = diag(m,1);
equivalently:
Result = diag(m,-1);
This is likely faster than an explicit loop, however I did not time it with a large matrix.

Kategorien

Mehr zu Descriptive Statistics finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by