How to speed up 2 loops with the intersect function?
显示 更早的评论
Hi
I have some code, which is very slow, because of the 2 loops. I was wondering if there was a clever way to speed this up? For example is it possible to somehow vectorize the following code? Thanks for your help!
for i=1:size(Lien,1)
k=1;
for j=1:size(Lien,1)
sommetscommuns=intersect(Lien(i,:),Lien(j,:));
if size(sommetscommuns,2)==2
voisins(i,k)=j;
k=k+1;
end
end
if voisins(i,1)~=0 && voisins(i,2)~=0 && voisins(i,3)~=0
Qnor(i,1) = (dot(Normales(i,:),Normales(voisins(i,1),:)) + ...
dot(Normales(i,:),Normales(voisins(i,2),:)) + ...
dot(Normales(i,:),Normales(voisins(i,3),:)))/3;
elseif voisins(i,1)~=0 && voisins(i,2)~=0 && voisins(i,3)==0
Qnor(i,1) = (dot(Normales(i,:),Normales(voisins(i,1),:)) + ...
dot(Normales(i,:),Normales(voisins(i,2),:)))/2;
elseif voisins(i,1)~=0 && voisins(i,2)==0 && voisins(i,3)==0
Qnor(i,1) = dot(Normales(i,:),Normales(voisins(i,1),:));
elseif voisins(i,1)==0 && voisins(i,2)==0 && voisins(i,3)==0
Qnor(i,1)=1;
end
end
the 'Lien' matrix is around 6300 rows...
2 个评论
What is in Lien? Integers within some range (what range?) or something more complex?
Also, in the first part of your loop, you're looking for rows that have exactly 2 elements in common with the current row. Do you ever expect more than 2?
From the second part of the loop, it looks like there's never more than 3 rows that have two elements in common with any row. Is that true?
You say your Lien matrix has ~6300 rows, but how many columns?
nicolas
2015-2-4
采纳的回答
更多回答(1 个)
If intersect is the bottleneck, take into account that it sorts the input every time. Then sort the columns of Lien once before the loop.
In older Matlab versions dot(x,y) was much slower than x*y'.
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!