how to reduce speed for 3 nested for loops.
7 views (last 30 days)
Show older comments
Ronak Narkhede
on 30 Apr 2023
Commented: Ronak Narkhede
on 30 Apr 2023

Is there a way I can reduce the overall computational time here? thanks
0 Comments
Accepted Answer
Richard Zappulla
on 30 Apr 2023
Edited: Richard Zappulla
on 30 Apr 2023
Morning!
When I ran your code, I got a time of about 6.55 seconds. The largest driver of run time are the round() function calls in the middle of your triple nested for loop.
If you take advantage of vectorized computations & logic operations, you can greatly reduce your run time (and number of lines!) by at least an order of magnitude. This can be accomplished by using the ndgrid function to generatethe combinations of t1, t2 & t3 that your triple-nested for loops would have provided.
You might want to consider the following refactoring. This produced a run time of about 0.70 (factor of 9.4x faster than your original code):
tic
range_t1 = (0:1:180)./57.2958;
range_t2 = (0:1:180)./57.2958;
range_t3 = (-90:1:90)./57.2958;
[t1, t2, t3] = ndgrid(range_t1, range_t2, range_t3);
x = round(140.*sin(t3).*sin(t2).*cos(t1) - 140.*cos(t3).*cos(t1).*cos(t2) - 180.*sin(t2).*cos(t1), 2);
y = round(119.6 + 140.*sin(t3).*sin(t1).*sin(t2) - 140.*cos(t3).*sin(t1).*cos(t2) - 180.*sin(t2).*sin(t1), 2);
z = round(-71.77 - 140.*sin(t3).*cos(t2) - 140.*cos(t3).*sin(t2) + 180.*cos(t2) + 117, 2);
logicInd = (x == 0) & (y == 0) & (z == 0);
a1 = t1(logicInd);
a2 = t2(logicInd);
a3 = t3(logicInd);
toc
More Answers (0)
See Also
Categories
Find more on Logical 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!