How can I efficiently vectorize a for-loop in MATLAB? Provide an example where vectorization significantly improves performance compared to a traditional loop.
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Tyo
el 31 de Jul. de 2023
Editada: Walter Roberson
el 22 de Ag. de 2023
How can I efficiently vectorize a for-loop in MATLAB? Provide an example where vectorization significantly improves performance compared to a traditional loop.
Respuesta aceptada
recent works
el 31 de Jul. de 2023
Editada: Walter Roberson
el 22 de Ag. de 2023
Example to calculate the cumulative sum of an array using a for-loop and its vectorized version:
% Sample array
arr = 1:100000;
% Using for-loop
tic;
sum_loop = 0;
for i = 1:length(arr)
sum_loop = sum_loop + arr(i);
end
time_loop = toc;
% Using vectorization
tic;
sum_vectorized = sum(arr);
time_vectorized = toc;
disp("Using for-loop: Sum = " + sum_loop + ", Time taken = " + time_loop + " seconds.");
disp("Using vectorization: Sum = " + sum_vectorized + ", Time taken = " + time_vectorized + " seconds.");
1 comentario
Les Beckham
el 31 de Jul. de 2023
In case someone want to actually see the results:
% Sample array
arr = 1:100000;
% Using for-loop
tic;
sum_loop = 0;
for i = 1:length(arr)
sum_loop = sum_loop + arr(i);
end
time_loop = toc;
% Using vectorization
tic;
sum_vectorized = sum(arr);
time_vectorized = toc;
disp("Using for-loop: Sum = " + sum_loop + ", Time taken = " + time_loop + " seconds.");
disp("Using vectorization: Sum = " + sum_vectorized + ", Time taken = " + time_vectorized + " seconds.");
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements 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!