Optimization of a nested loop

3 visualizaciones (últimos 30 días)
Italo
Italo el 22 de Jun. de 2012
Hello guys I wrote the following code, but it takes ages to complete. Could you please help me optimizing it? A and B are matrixes
for i=1:length(A)
for j=1:length(B)
CCI = CCI + heaviside(norm(A(i,:)-B(j,:)));
end
end
Thanks

Respuestas (2)

Sean de Wolski
Sean de Wolski el 22 de Jun. de 2012
Not necessarily faster, prettier, less confusing or better in any way with the exception of being on one line and containing the awesomeness that is bsxfun:
CCI2 = sum(sum(heaviside(sqrt(sum(bsxfun(@minus,A,reshape(B',1,size(B,2),size(B,1))).^2,2)))))

Andrei Bobrov
Andrei Bobrov el 22 de Jun. de 2012
other variant
CCI = (nnz(any(bsxfun(@minus,A,reshape(B',1,size(B,2),[])),2)) + size(A,1)*size(B,1))/2;

Categorías

Más información sobre Direct Search en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by