For-loop vectorization

Hello people, I'm sort of a novice matlab user at best. Then, How to effectively vectorize the loop in this code?
se = strel('diamond',2);
row = size(P, 1); % where P is a RGB image
col = size(P, 2);
crist = zeros(row,col, 1);
num = sum(sum(S)); % where S is a binary image (P and S have the same size)
[Y, X]=find(S, num);
for i = 1:num
x1 = X(i);
y1 = Y(i);
d1 = tdist3D(P, x1, y1);
t1 = d1 < dist; % where dist is a threshold number defined by the user
crist = or(crist, bwselect(bwmorph(imerode(t1, se), 'close', 2), x1, y1, 4));
end
.....
where, tdist3D is the fallowing function:
function J=tdist3D(A,x,y)
% Distance transformation between the RGB image pixels and
% the (x,y) pixel of the binary image.
%
% Syntax:
% J = tdist3D(A,x,y)
%
% Input:
% A: image RGB
% x,y: pixel of the binary image
%
% Output:
% J: image distance
temp = ones(size(A));
Ref = cat(3, temp(:, :, 1).*A(y, x, 1), temp(:, :, 1).*A(y, x, 2), temp(:, :, 1).*A(y, x, 3));
D = A - Ref;
D2 = D.^2;
SD2 = sum(D2, 3);
J = SD2.^0.5;
Thank in advance for any help.
JulioC

Answers (1)

Jan
Jan on 8 Nov 2012
  • sqrt() is much faster than ^0.5.
  • When you do not need the 3rd component of temp, do not create it:
temp = ones(size(A, 1), size(A, 2));
  • What is the reason to multiply by ONES?! A multiplication with a scalar 1 would be much faster. But I guess you want a converion to a double? Then use double(A).
  • The bottlenecks of your program are bwselect, bwmorph and imerode. Therefore a vectorization will not help noticably.

Asked:

on 8 Nov 2012

Community Treasure Hunt

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

Start Hunting!