How do I create a vector of the average of consecutive elements of another vector (without using a loop)?
Mostra commenti meno recenti
Say, I have a vector A=[2 4 6 8 10]. Is there any way I can create a vector of the average of consecutive elements of A, i.e. B=[3 5 7 9] without using a loop? Is there any matlab function to do that? Thanks in advance.
Risposta accettata
Più risposte (2)
This is simpler and occupies less temporary memory than Azzi's approach:
A = [2 4 6 8 10];
B = 0.5 * (A(1:end-1) + A(2:end))
1 Commento
Rinu
il 11 Ott 2013
Matthew Crema
il 10 Ott 2013
One way:
A=[2 4 6 8 10];
foo = conv([1 1], A)/2;
B = foo(2:end-1)
B =
3 5 7 9
-Matt
5 Commenti
Rinu
il 10 Ott 2013
Jan
il 10 Ott 2013
Instead of dividing the array after the application of conv, you can divide the parameters instead: conv([0.5, 0.5], A) . The avoids the expensive division of all array elements.
Matthew Crema
il 11 Ott 2013
Yup. But I agree that the use of indexing seems better with respect to readability and marginally better speed.
Jan
il 11 Ott 2013
The speed argument might change, when the data exceed a certain size.
Andrei Bobrov
il 11 Ott 2013
Modificato: Andrei Bobrov
il 11 Ott 2013
conv2(A,[.5 .5],'valid')
Categorie
Scopri di più su Logical 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!