Efficient way to calculate backwards average
Mostra commenti meno recenti
Dear all,
I'm looking for an efficient way to calculate a backwards moving average, i.e., giving a vector A I want to calculate a vector A2 for which the element i is equal to mean(A(i:end)).
For the moment I am doing it this way:
A=rand(1,1000);
n=length(A);
A2=zeros(1,n)
for i=1:n
A2(i)=mean(A(i:end));
end
Is there any better way?
Thanks
Lorenzo
Risposta accettata
Più risposte (4)
Chad Greene
il 29 Set 2014
0 voti
This is a very fast moving average calculator. It centers data, so if you use an N-point moving average, after calculating the moving averaged, you could shift by N/2 to get the "backwards" moving average.
1 Commento
Image Analyst
il 29 Set 2014
He doesn't want a moving average. His window is not constant length, but gets shorter as the index approaches the end of the array.
s = sum(A);
n = length(A);
A2 = (s - cumsum(A))/n;
is a little more elegant and I would think faster. But you have to add s/N to the beginning of A2 and remove the 0 at the end of A2.
The last operation (removing the zero) is misleadingly innocent:
A2(end) = [];
But you may soon get to know the consequences of it.
1 Commento
Lorenzo
il 30 Set 2014
1 Commento
Stephen23
il 30 Set 2014
Unless you are actually answering your own question, write a comment to your original question or one of the answers. There is no guarantee that the answers remain in any particular order...
Categorie
Scopri di più su Matrix Indexing in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!