i need help vectorizing this loop

조회 수: 9 (최근 30일)
leon
leon 2019년 4월 2일
편집: Adam Danz 2019년 4월 2일
N = 16;
S = randi(2,[N,N])*2-3;
for l = 1:(N/2-1)
Sl = circshift(S,[l,l]);
f(l) = 1/N*sum(sum(S*Sl.'));
end

답변 (1개)

Adam Danz
Adam Danz 2019년 4월 2일
You can't vectorize the circular shift so there's no way to get out of using the for-loop. It's fast, relatively concise, and easy to read so a for-loop isn't a problem here.
If you require that N is an even number, you should include an assumption check to ensure this is always the case instead of just hoping.
% Ensure N is even
if rem(N,2)~=0
error('The value of N is not even.')
end
Also, you should allocate the f variable before the loop.
f = nan(1, N/2-1);
  댓글 수: 2
leon
leon 2019년 4월 2일
the reason why i was trying to avoid the for loop i because i am running a montecarlo simulation of a 2-d ising model with 1e6 mc steps, so every microsecond counts here.
if i write a function i will be sure to include it.
i made sure to do that in the original code and just forgot to put it here.
thank you for your response !
Adam Danz
Adam Danz 2019년 4월 2일
편집: Adam Danz 2019년 4월 2일
I'm not sure how much time this will save but one suggestion is to move the circshift into the sum() function rather than assigning that variable on each iteration.
for l = 1:(N/2-1)
f(l) = 1/N*sum(sum(S * circshift(S,[l,l]).'));
end
I have a custom function that compares timing between two sets of code and performs statistics to determine if one is faster. For what it's worth, I timed both versions (one with cirshift embedded and one with circshift separate) and ran it 1 million times each. The embedded version was 1.054 times faster and saved less than 0.0001 seconds (p=0.000, wilcox rank sum). So there was barely a difference. Each for-loop consumed ~0.00005 sec on average.

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

카테고리

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

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by