Efficient calculation of 3d matrix of distances

1 回表示 (過去 30 日間)
Luis Isaac
Luis Isaac 2016 年 8 月 3 日
コメント済み: Adam 2016 年 8 月 3 日
Dear;
I would like to calculate the 3D matrix of distances between one point an each element of a 3D matrix in an efficient way.
Without vectorization the code is:
MDistances=zeros(size(M));
for i=1:size(M,1)
for j=1:size(M,2)
for k=1:size(M,3)
MDistances(i,j,k)=(i-ip)^2+(j-jp)^2+(k-kp)^2
end
end
end
MDistances=sqrt(MDistances);
Thanks a lot!!

採用された回答

Adam
Adam 2016 年 8 月 3 日
[x, y, z] = meshgrid( (j-jp)^2, (i-ip)^2, (k-kp)^2 );
distSq = x + y + z;
MDistances = sqrt( distSq );
should give the correct answer I think. I always get confused with meshgrid though how my x and y inputs and outputs always seem to be the wrong way round. When I did the obvious approach I ended up with an answer that didn't match expectations so swapping i and j around in the inputs seems to give the right answer.
Maybe someone else can expand on why that is the case as I don't have the time to re-remember!
  2 件のコメント
Luis Isaac
Luis Isaac 2016 年 8 月 3 日
Great answered!! The only evident thing is that i,j and k must be integer vector now:
i=1:size(M,1);
j=1:size(M,2);
k=1:size(M,3);
[x, y, z] = meshgrid( (j-jp)^2, (i-ip)^2, (k-kp)^2 );
distSq = x + y + z;
MDistances = sqrt( distSq );
Adam
Adam 2016 年 8 月 3 日
Ah yes, I forgot to include that I had created those in the same way you do for each of your loops.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by