For Loop taking too long to execute.

3 visualizaciones (últimos 30 días)
Salman Saeed
Salman Saeed el 25 de Ag. de 2015
Comentada: Walter Roberson el 25 de Ag. de 2015
My for loops are taking too long to execute. I am writing my code here. Is there any possibility of improving my code so that it takes less time or can I completely bypass the for loops?
Transitionbwd = zeros(2048,11) ;
StateTransitionbwd = zeros(2048,2048);
for k = 1:2048
for l = 1:11
for i = 1:2048
for j = 1:11
if inputfwd(k,l) == 0
Transitionfwd(i,j) = 1 - 0.001;
elseif norm(Statesfwd(k,l) - sjfwd(i,j)) == Statesfwd(k,l)
Transitionfwd(i,j) = 0.5 - 0.5*tanh(0.5 * inputfwd(k,l));
else
Transitionfwd(i,j) = 0.5 + 0.5*tanh(0.5 * inputfwd(k,l));
end
end
end
dim = 2;
StateTransitionfwd(k,:) = prod(Transitionfwd,2);
end
end

Respuesta aceptada

Walter Roberson
Walter Roberson el 25 de Ag. de 2015
You could remove your
elseif norm(Statesfwd(k,l) - sjfwd(i,j)) == Statesfwd(k,l)
and the associated action. Due to numeric roundoff in finite precision binary floating point, values computed in even slightly different ways will seldom compare as equal for the purposes of "==". The "==" comparison checks for bit-wise identical (non-NaN) numbers. As you will only get equality by accident, you might as well remove that test.
I am assuming here that you consider your existing loops to be correct but just too slow. There is an alternative interpretation, which is that your existing code is not correct, and that instead of comparing using "==" you want to check to see if the norm is "close to" the stored value, for some definition of "close to".
  2 comentarios
Salman Saeed
Salman Saeed el 25 de Ag. de 2015
Actually Statesfwd(k,l) and sjfwd(i,j) are 0 or 1. I want to use the mentioned formula if sjfwd(i,j) is 0. Do you think it can still have the same problem of floating points?
Walter Roberson
Walter Roberson el 25 de Ag. de 2015
Why not just test if sjfwd(i,j) == 0 ?

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements 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