Producing a Matrix

4 ビュー (過去 30 日間)
M
M 2011 年 5 月 19 日
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.

採用された回答

Teja Muppirala
Teja Muppirala 2011 年 5 月 19 日
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]));

その他の回答 (2 件)

Yoav Livneh
Yoav Livneh 2011 年 5 月 19 日
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 2011 年 5 月 19 日
Thank you both very much.
Your solutions work very well

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by