Efficiency fix

6 visualizaciones (últimos 30 días)
Andy
Andy el 13 de En. de 2012
Hi, another efficiency fix needed. this one runs over 20 second everytime. would be a big help if that nested loop could be shortened somehow.Thanks!
counter3 = 1;
for n = 1: length(mymatrix2(1,:))
for p = 1:length(mymatrix2(1,:))
if abs (mymatrix2(1,n) - mymatrix2(1,p)) == 1;
if mymatrix2(2,n) >= mymatrix2(2,p) ;
if ismember ( mymatrix(1,n), replacewith) == false
replacewith(counter3) = mymatrix2(1, n);
end
elseif mymatrix2(2,p) >=mymatrix2(2,n);
if ismember (mymatrix(1,p), replacewith) == false
replacewith(counter3) = mymatrix2(1,p);
end
end
counter3 = counter3 +1;
end
end
end
  1 comentario
Walter Roberson
Walter Roberson el 13 de En. de 2012
Andy, I had to edit a fair bit to make the code readable. Please be especially careful about trailing blanks on the line: if they fall in just the wrong place then things might look right as you enter the code in, but look bad in the finished message. Best is not to have trailing blanks.
I left in the semi-colon you have at the end of an "if" and an "elseif" line. Those semi-colon are not necessary.

Iniciar sesión para comentar.

Respuesta aceptada

Jan
Jan el 14 de En. de 2012
Some simplifications at first:
counter3 = 1;
len = size(mymatrix2, 2);
for n = 1:len
a = mymatrix(1, n);
for p = 1:len
b = mymatrix2(1,p);
if abs(a - b) == 1
if mymatrix2(2,n) >= mymatrix2(2,p)
if ~any(a == replacewith)
replacewith(counter3) = a;
end
elseif mymatrix2(2,p) >= mymatrix2(2,n);
if ~any(b == replacewith)
replacewith(counter3) = b;
end
end
counter3 = counter3 + 1;
end
end
end
But I'm sure this profits from vectorization. Please post meaningful test data - a RAND is preferred.

Más respuestas (0)

Categorías

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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by