how to reduce speed for 3 nested for loops.
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Ronak Narkhede
el 30 de Abr. de 2023
Comentada: Ronak Narkhede
el 30 de Abr. de 2023

Is there a way I can reduce the overall computational time here? thanks
0 comentarios
Respuesta aceptada
Richard Zappulla
el 30 de Abr. de 2023
Editada: Richard Zappulla
el 30 de Abr. de 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
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!