How to vectorize the MATLAB code?

조회 수: 6 (최근 30일)
Sam Yeoh
Sam Yeoh 2022년 2월 14일
댓글: Jan 2022년 2월 14일
This is the code that I have written and I saw articles about vectorization.
N = length(a);
b = zeros(1,N - 1);
for i = 1:N-1
b(i) = a(i) + a (i + 1);
end
How should I vectorize my code in this circumstance? Any suggestions? Thank you.

채택된 답변

Jan
Jan 2022년 2월 14일
편집: Jan 2022년 2월 14일
a = rand(1, 11);
N = length(a);
b = zeros(1,N - 1);
for i = 1:N-1
b(i) = a(i) + a (i + 1);
end
% Vectorized 1:
b2 = a(1:end-1) + a(2:end);
% Vectorized 2:
b3 = conv(a, [1,1], 'valid')
% [EDITED] % Vectorized 3: Working only for even length of a!
% [EDITED] b4 = sum(reshape(a, 2, [])); % Not the same result!
% Thanks John D'Errico.
isequal(b, b2, b3)
ans = logical
1
For a = rand(1,1e6) and 100 repetitions, Matlab 2018b needs:
% Elapsed time is 0.683647 seconds. loop
% Elapsed time is 0.874940 seconds. 1:end-1 + 2:end
% Elapsed time is 0.477227 seconds. conv
You see, that vectorization is not a standard trick for accelerating code. The memory access can take more time than the loop.
  댓글 수: 3
John D'Errico
John D'Errico 2022년 2월 14일
While I gave a +1 to @Jan for the answer, b4 is incorrect.
a = rand(1, 10);
b3 = conv(a, [1,1], 'valid')
b3 = 1×9
1.0363 1.0664 0.8794 0.4572 0.8286 1.0839 0.8633 0.9137 0.8310
% Vectorized 3: Working only for even length of a!
b4 = sum(reshape(a, 2, []));
b3
b3 = 1×9
1.0363 1.0664 0.8794 0.4572 0.8286 1.0839 0.8633 0.9137 0.8310
b4
b4 = 1×5
1.0363 0.8794 0.8286 0.8633 0.8310
b4 sums the 1st and second, but NOT the 2nd and 3rd elements.
Jan
Jan 2022년 2월 14일
Thanks, John.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by