How to reduce For loop execution time?
Show older comments
I have following Matlab code to calculate summation of exponential summation term:
This code takes approx. 600 seconds to give final output s. Is there any way to reduce this computation time?
sum1 = 0;
s = 0;
for i=1:1000000000
for j=1:3
sum1 = sum1+(i*proc(j))^2;
end
s = s+exp(-sum1);
end
7 Comments
Walter Roberson
on 5 Dec 2019
We recommend that you do not use sum as the name of a variable, as it interferes with using the common function sum() . It is quite common that when sum is used as a variable name, that at some point the user will also want to use sum() as a function.
Ajinkya Bankar
on 5 Dec 2019
Edited: Ajinkya Bankar
on 5 Dec 2019
Rik
on 5 Dec 2019
At least you can replace your inner loop (assuming proc(j) returns the same output every time it is called with the same input). But I don't see an easy way to replace the outer loop. Can you confirm this is the way your code should work? Because it would be a lot easier if sum1 would be set to 0 inside the outer loop.
Walter Roberson
on 5 Dec 2019
Godo point, Rik. The code I posted does do the equivalent of assuming that sum1 is set to 0 inside the outer for loop.
Ajinkya Bankar
on 5 Dec 2019
Steven Lord
on 5 Dec 2019
What is the mathematical (not code) expression of what you're trying to compute with this code? Or do you have a description in words of what you're trying to compute? That might help us understand what the right result is and find an efficient way to compute that right result.
Also, what are the contents of the variable proc? When you get to the last iterations of the outer loops, you're adding an extremely large number to sum1 unless the elements of proc are very small. You might be able to stop the outer loop sooner if sum1 is so large that exp(-sum1) underflows to 0.
y = 750;
exp(-y) % 0
Ajinkya Bankar
on 6 Dec 2019
Accepted Answer
More Answers (0)
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!