codes instead of 'for' loops to speed up
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Jan
le 18 Août 2012
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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Graphics Performance dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!