I have an array (of size 2958 x 1). I want to average every five separate element from starting and store the result into a new array. For example:
arr = (1:10).'; % for this array
avg = [3; 8]; % this should be the result
How can I do this?
I have an array (of size 2958 x 1). I want to average every five separate element from starting and store the result into a new array. For example:
arr = (1:10).'; % for this array
avg = [3; 8]; % this should be the result
How can I do this?
One way to calculate the average of every n
element in an array is using arrayfun
:
n = 5;
arr = rand(2958,1); % your array
avg = arrayfun(@(ii) mean(arr(ii:ii + n - 1)), 1:n:length(arr) - n + 1)';
Update:
This works much faster:
avg = mean(reshape(arr(1:n * floor(numel(arr) / n)), [], n), 2);
The difference is BIG:
------------------- With ARRAYFUN
Elapsed time is 4.474244 seconds.
------------------- With RESHAPE
Elapsed time is 0.013584 seconds.
The reason for arrayfun
being so slow here is that I am not using it properly. arr(ii:ii + n - 1)
creates an array in memory and it happens many times. The reshape
approach on the other hand works seamlessly as it should.