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!