Optimizing a distance calculation for elements within a matrix
8 ビュー (過去 30 日間)
古いコメントを表示
Following up with my series of questions, I now have a new one. Lets recap,I have a three dimensional matrix of size (x,j,k). This matrix is composed of three values (0, 122, and 255). I am interested in calculating the minimum distance for elements with a value of 122 and 255 to its closest zero element. Below is what I have thus far. The code works, but it is excruciatingly slow. The convolution is used to eliminate unnecessary zero elements for the code to consider which helps a bit. The lines following the y for loop help A LOT by forcing the code to only consider local elements and not looking at the whole matrix. This chunk of code spends most of its time calculating distance (Around 60% of the time). The next big consumption of time is when the code calculates index. The tradeoff here is that if it were not for the variable index this would take forever.
% This section of the code is purely to optimize save some time %
mc=convn(padarray(m,[1 1 1],1),ones(3,3,3),'valid');
locations=find(mc==0);
m(locations)=1;
IND=find(m==0);
s=[x_voxels,y_voxels,z_voxels];
[null_index(:,1),null_index(:,2),null_index(:,3)]=ind2sub(s,IND);
for z=1:z_voxels;
for y=1:y_voxels;
highy=(y_voxels-(y_voxels-(y+8)));
lowy=y-8;
highz=(z_voxels-(z_voxels-(z+8)));
lowz=z-8;
index=find(null_index(:,2)<=highy & null_index(:,2)>=lowy & ...
null_index(:,3)<=highz & null_index(:,3)>=lowz); %See comment 1
if 1==exist('index','var');
distance=zeros(size(index,1),1);
end
for x=1:x_voxels;
if m(x,y,z)~=0 && m(x,y,z)~=1;
distance(:,1)=sqrt((x-null_index(index,1)).^2+...
(y-null_index(index,2)).^2+...
(z-null_index(index,3)).^2);
min_dist=min(distance);
Thanks for the help guys.
Dave
0 件のコメント
採用された回答
Sean de Wolski
2013 年 5 月 10 日
Have you considered using the distance transform in the Image Processing Toolbox?
doc bwdist
This is highly optimized and can run pretty quickly on big data.
その他の回答 (1 件)
参考
カテゴリ
Help Center および File Exchange で Multidimensional Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!