Decreasing the computing time of the for loop

2 views (last 30 days)
Hello,
I am looking for some help to deal with this loop, and speed up the computing time. Would anyone have some advice as to how I can make it more efficient as I have already tried preallocation so I think it is the if statement that is slowing down the computing time.
A = zeros(1069,30659,16);
idx = reshape(1:16,4,4);
for j = 1:4
for k = 1:4
for n = 1:30658
for i = 1+j:(1069-k)
if ~isnan(logRet(i-j:i-1,n))
if nansum(logRet(i-j:i-1,n)) < 0
A(i+k,n,idx(j,k)) = -1*(logRet(i+k,n));
else
A(i+k,n,idx(j,k)) = (logRet(i+k,n));
end
end
end
end
end
end
Another question that I have is say if I wanted to loop from for j =1:12, and for k = 1:12, the end result would provide me with too large of a matrix so how would I be able to achieve this? Would it be to break up the loop?
Any help is appreciated and thanks in advance.

Answers (1)

Walter Roberson
Walter Roberson on 20 Feb 2016
In your
if ~isnan(logRet(i-j:i-1,n))
that is the same as
if all(~isnan(logRet(i-j:i-1,n)))
which will only succeed if none of the entries are nan. But if none of the entries are nan, then there is no point in using nansum() on the next line when it would be more efficient to use sum().
Also, look a bit more closely and notice that idx(j,k) is not varying in the "for i" loop, or in the "for n" loop that surrounds that. It would therefore be more efficient to assign idx(j,k) to a variable each time that k changes, and use that variable instead of recalculating idx(j,k) each time.
  2 Comments
Putsandcalls
Putsandcalls on 20 Feb 2016
Unfortunately, I have a bunch of NaN's segregated everywhere. I guess I will just have to wait it out or break down the tasks.
Walter Roberson
Walter Roberson on 20 Feb 2016
When "if ~isnan(logRet(i-j:i-1,n))" is true, none of the entries in logRet(i-j:i-1,n) can possibly be NaN, because the "if" would fail if any of the values in "~isnan(logRet(i-j:i-1,n))" were false, which would occur if any of logRet(i-j:i-1,n) are nan.
So, under the condition that none of logRet(i-j:i-1,n), which is protected against by your "if", then you can use sum() instead of nansum()

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!