For Loop taking too long to execute.

1 回表示 (過去 30 日間)
Salman Saeed
Salman Saeed 2015 年 8 月 25 日
コメント済み: Walter Roberson 2015 年 8 月 25 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by