필터 지우기
필터 지우기

Producing a Matrix

조회 수: 1 (최근 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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by