For Loop taking too long to execute.

1 次查看(过去 30 天)
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

采纳的回答

Walter Roberson
Walter Roberson 2015-8-25
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 个评论
Salman Saeed
Salman Saeed 2015-8-25
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 2015-8-25
Why not just test if sjfwd(i,j) == 0 ?

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by