matlab - (non-overlapping moving) Average of every n element in a vector -
this question has answer here:
i have array (of size 2958 x 1). want average every 5 separate element starting , store result new array. example:
arr = (1:10).'; % array avg = [3; 8]; % should result
how can this?
one way calculate average of every n
element in array using arrayfun
:
n = 5; arr = rand(2958,1); % array avg = arrayfun(@(ii) mean(arr(ii:ii + n - 1)), 1:n:length(arr) - n + 1)';
update:
this works faster:
avg = mean(reshape(arr(1:n * floor(numel(arr) / n)), [], n), 2);
the difference big:
------------------- arrayfun elapsed time 4.474244 seconds. ------------------- reshape elapsed time 0.013584 seconds.
the reason arrayfun
being slow here not using properly. arr(ii:ii + n - 1)
creates array in memory , happens many times. reshape
approach on other hand works seamlessly should.
Comments
Post a Comment