Borrar filtros
Borrar filtros

Producing a Matrix

1 visualización (últimos 30 días)
M
M el 19 de Mayo de 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.

Respuesta aceptada

Teja Muppirala
Teja Muppirala el 19 de Mayo de 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]));

Más respuestas (2)

Yoav Livneh
Yoav Livneh el 19 de Mayo de 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 el 19 de Mayo de 2011
Thank you both very much.
Your solutions work very well

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by