How to average 5 rows of a vector recursively?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Samuel White
am 30 Jan. 2019
Kommentiert: Ollie A
am 30 Jan. 2019
I have a very long 1D vector ~ 9445 long. I wish to take the average of sets of 5 down the vector and send them to a new vector for example:
1
2
3
4
5
6
7
8
9
10
would become
3
8
How can I do this easily?
Many thanks
0 Kommentare
Akzeptierte Antwort
Ollie A
am 30 Jan. 2019
Bearbeitet: Ollie A
am 30 Jan. 2019
V = 1:9445; % Your vector
setsize = 5;
for x = 1:length(V)/setsize
Vnew(x) = mean(V((x-1)*setsize+1:x*setsize))
end
I hope this is simple enough.
4 Kommentare
Guillaume
am 30 Jan. 2019
It's unfortunate you've accepted that answer which is overly complicated and slow and not the matlab way. The lack of preallocation of the output is also going to be a problem if you're not careful.
However, as long as Vnew did not exist before running that code, it will produce a vector.
For the proper way to do what you want in matlab, see my answer.
Weitere Antworten (1)
Guillaume
am 30 Jan. 2019
As long as the length of your vector is a multiple of 5:
mean(reshape(yourvector, 5, []), 1)
If the length is not a multiple of 5, pad it first with NaNs to a multiple of 5 and do the same as above, with the 'omitnan' flag for mean:
paddedvector = [yourvector; nan(mod(-numel(yourvector), 5), 1)]; %pad to a length multiple of 5
mean(reshape(paddedvector, 5, []), 1, 'omitnan')
0 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!