MATLAB: Producing a Matrix

distancefor loopmatrixsphere

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.

Best Answer

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]));