How to speed up 2 loops with the intersect function?
Mostra commenti meno recenti
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 Commenti
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
il 4 Feb 2015
Risposta accettata
Più risposte (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'.
1 Commento
nicolas
il 4 Feb 2015
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!