How to average 5 rows of a vector recursively?
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Ollie A
2019 年 1 月 30 日
編集済み: Ollie A
2019 年 1 月 30 日
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 件のコメント
Guillaume
2019 年 1 月 30 日
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.
その他の回答 (1 件)
Guillaume
2019 年 1 月 30 日
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!