Effacer les filtres
Effacer les filtres

Producing a Matrix

1 vue (au cours des 30 derniers jours)
M
M le 19 Mai 2011
Hello,
I have three vectors of length 1000 which contain the X,Y and Z coordinates of the centers of 1000 spheres. I want to produce a 1000 x 1000 matrix which contains the distance between each sphere.
i.e. Matrix(2,1) is the distance between the 2nd and 1st sphere Matrix(2,15) is the distance between the 2nd and 15th sphere.
This matrix will be a symmetric matrix i.e. Matrix(1,2)=Matrix(2,1)
Can anyone tell me how i could make this matrix in a single line of code without the use of a for loop. I dont want to use a for loop to reduce processing time.

Réponse acceptée

Teja Muppirala
Teja Muppirala le 19 Mai 2011
FAST:
[Xa, Xb]=meshgrid(X);
[Ya, Yb]=meshgrid(Y);
[Za, Zb]=meshgrid(Z);
D = sqrt((Xa-Xb).^2+(Ya-Yb).^2+(Za-Zb).^2);
FASTER:
D = sqrt(bsxfun(@minus,X',X).^2+bsxfun(@minus,Y',Y).^2+bsxfun(@minus,Z',Z).^2);
FASTEST (as far as I know):
D = squareform(pdist([X Y Z]));

Plus de réponses (2)

Yoav Livneh
Yoav Livneh le 19 Mai 2011
I believe you are looking for meshgrid:
[Xa, Xb]=meshgrid(X);
[Ya, Yb]=meshgrid(Y);
[Za, Zb]=meshgrid(Z);
Dist = sqrt((Xa-Xb).^2+(Ya-Yb).^2+(Za-Zb).^2);

M
M le 19 Mai 2011
Thank you both very much.
Your solutions work very well

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by