How can I efficiently vectorize a for-loop in MATLAB? Provide an example where vectorization significantly improves performance compared to a traditional loop.

조회 수: 2 (최근 30일)
How can I efficiently vectorize a for-loop in MATLAB? Provide an example where vectorization significantly improves performance compared to a traditional loop.

채택된 답변

recent works
recent works 2023년 7월 31일
편집: Walter Roberson 2023년 8월 22일
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
Les Beckham
Les Beckham 2023년 7월 31일
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.");
Using for-loop: Sum = 5000050000, Time taken = 0.019152 seconds.
disp("Using vectorization: Sum = " + sum_vectorized + ", Time taken = " + time_vectorized + " seconds.");
Using vectorization: Sum = 5000050000, Time taken = 0.001957 seconds.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by