Optimizing a distance calculation for elements within a matrix

2 views (last 30 days)
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

Accepted Answer

Sean de Wolski
Sean de Wolski on 10 May 2013
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.
  2 Comments
David
David on 10 May 2013
Alright, let me give that a try and see what I can do. I'll let you know what happens.

Sign in to comment.

More Answers (1)

David
David on 10 May 2013
I guess, I am just going to use the parallel computing toolbox for this. I would still welcome any suggestions to speed this up.
Dave

Community Treasure Hunt

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

Start Hunting!