Trying to avoid a simple triple for loop.
1 次查看(过去 30 天)
显示 更早的评论
Dearest Matlab users,
I'm trying to simplify the following simple code, because as you may observe is running really slow when called multiple (~1M) times. What I would like to do is simply check the surroundings (cubes of increasing size 3x3x3,5x5x5,...) of a voxel on a 3D volume, counting the number of voxels in the surrounding that are 1,0 and -1.
Thanks so much for any advice you may suggest to speed up this code :)
cubedims = [3 5 9 15];
conts = zeros(3,4);
%Given a point [xi yi zi]
for ic = 1:ncubs
lad = cubedims(ic);
for xi = 1:lad
for yi=1:lad
for zi=1:lad
if sum([xi yi zi] > 0) == 3 && sum([xi yi zi] <= lasizev) == 3
switch testmask(xi,yi,zi) %this is a 3D volume
case 1
conts(1,ic) = conts(1,ic)+1;
case 0
conts(2,ic) = conts(2,ic)+1;
case -1
conts(3,ic) = conts(3,ic)+1;
end
end
end
end
end
conts(:,ic) = conts(:,ic) ./ (lad*lad*lad);
end
0 个评论
回答(1 个)
Daniel Shub
2013-4-3
编辑:Daniel Shub
2013-4-3
It looks like you can eliminate the first part of the if statement since xi, yi and zi are always greater than 0. Instead of looping all the way to lad, you can stop at lasizev. You can then eliminate the if statement. Finally, you can also replace the switch statement with conts(2-testmask(...), ic).
This then leads to an vectorised solution which may or may not be faster:
conts(1, ic) = sum(testmask(1:lasizev, 1:lasizev, 1:lasizev))==1;
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Object Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!