codes instead of 'for' loops to speed up

조회 수: 9 (최근 30일)
Coo Boo
Coo Boo 2012년 8월 18일
Hi to all,
I have 3 'for' loop which make the excutation to be time-consuming. Is there any way to speed up? The code is:
...
for i= 0:P
for j=0:P
ss=0;
for k=P:N-1
ss=ss+x(k-j+1,1)*x(k-i+1,1);
end
R(i+1,j+1)=ss;
end
end
...
Thanks,
  댓글 수: 3
Jan
Jan 2012년 8월 18일
Hi Matt! I'm happy to see you back again.
Matt Fig
Matt Fig 2012년 8월 18일
Hello Jan!

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

채택된 답변

Jan
Jan 2012년 8월 18일
as Matt has mentioned already, the question does not contain enough information to be answered exhaustively. The simple approach to vectorize the innermost loop is most likely not efficient:
for i = 0:P
for j = 0:P
R(i+1, j+1) = sum(x(P-j+1:N-j, 1) .* x(P-i+1:N-i, 1));
end
end
Now the creation of the intermediate vectors x(P-j+1:N-j, 1) takes too much time - but this is a guess only, which I cannot prove due to the missing details in the question.
But you could try to store one of the vectors in a temporary variable:
for i = 0:P
t1 = x(P-i+1:N-i, 1);
for j = 0:P
R(i+1, j+1) = sum(x(P-j+1:N-j, 1) .* t1);
end
end
Then you should exploit the symmetric structure of the result:
for i = 0:P
t1 = x(P-i+1:N-i, 1);
R(i+1, i+1) = sum(t1 .* t1); % Diagonal element
for j = i+1:P
t2 = sum(x(P-j+1:N-j, 1) .* t1);
R(i+1, j+1) = t2;
R(j+1, i+1) = t2;
end
end
Again: I cannot test this code. Please post requests for optimizing code always with a set of usual test data. Most likely the SUM(vector1 .* vector2) approach is slower than a lean and clean loop. Therefore I assume that exploiting the symmetry is a more useful strategy.
Omitting the 2nd index in "x(k, 1)" saves time, if x is a vector. But perhaps x is a function and the 2nd input is important.
  댓글 수: 1
Coo Boo
Coo Boo 2012년 8월 19일
Thanks for your pefect answer.

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

추가 답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by