# Conversion of for loop to Vector.

3 views (last 30 days)
azizullah khan on 16 Dec 2015
Commented: azizullah khan on 17 Dec 2015
I have two for loops and it's processing is very slow.I need to speed up the task. Any help would be highly appreciated.
for i=1:ll
for j=1:ll
X=[a(i),b(i);a(j),b(j)];
d = pdist(X,'euclidean');
if d>0 && d<(4.1*ro)
if k2(a(i),b(i))>k2(a(j),b(j))
k3(a(j),b(j))=0;
end;
if k2(a(i),b(i))<k2(a(j),b(j))
k3(a(i),b(i))=0;
end;
end;
end;
end;
Thank you,,,,
Guillaume on 16 Dec 2015
What I meant is that you should have a description of the purpose of each line of code. Ideally, this should be comments in the code itself.
I can guarantee you won't have a clue how the code above does its job if you come back to it in a year.

Guillaume on 16 Dec 2015
Here is something that I believe does the same as your code. Added bonus, it's got comments:
ll = 20; %size of matrices, maximum value of a and b vectors
%generate some demo data, since you didn't provide any:
a = randperm(ll); %a is row coordinates of matrices corresponding to ... something
b = randperm(ll); %b is column coordinates of matrices corresponding to ... something
k2 = rand(ll); %k2 is a matrix corresponding to ...?
k3 = ones(ll); %don't know what that is.
ro = 3; %threshold scale below which something (?) happen
%compute euclidean distance between all the points made by corresponding (a,b) pairs:
d = hypot(bsxfun(@minus, b, b'), bsxfun(@minus, a, a')); %equivalent to your pdist
%find which distances are within the threshold
[row, col] = find(d>0 & d<4.1*ro); %correspond to your if d ...
%find which of the two pixels of k2 defined by [a(row), b(row)] and [a(col), b(col)] is the smallest:
s = sign(k2(sub2ind(size(k2), a(row), b(row))) - k2(sub2ind(size(k2), a(col), b(col)))); %equivalent to your two if k2...
%s is 1 when it's the column pixel that is smaller, -1 when it's the row pixel, and 0 when both equal
%set corresponding pixel to 0 in k3:
k3(sub2ind(size(k3), a(col(s == 1)), b(col(s == 1)))) = 0;
k3(sub2ind(size(k3), a(row(s == -1)), b(row(s == -1)))) = 0;
azizullah khan on 17 Dec 2015
Thank you, I got luck , my prob is solved!!!

Renato Agurto on 16 Dec 2015
Hello,
I would try this under the assumjption that:
pdist(X1,'euclidean') == pdist(X2,'euclidean')
if:
X1 = [a(i),b(i);a(j),b(j)];
X2 = [a(j),b(j);a(i),b(i)];
Code:
for i=1:ll
for j=i+1:ll
X=[a(i),b(i);a(j),b(j)];
d = pdist(X,'euclidean');
if d>0 && d<(4.1*ro)
if k2(a(i),b(i))>k2(a(j),b(j))
k3(a(j),b(j))=0;
elseif k2(a(i),b(i))<k2(a(j),b(j))
k3(a(i),b(i))=0;
end;
end;
end;
end;
##### 2 CommentsShowHide 1 older comment
Guillaume on 16 Dec 2015
As I've shown in my answer you can calculate the euclidean distance between all points in one go with just one line:
d = hypot(bsxfun(@minus, b, b'), bsxfun(@minus, a, a'))
The loops, the pdist, the if, all of this is unnecessary.