1

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?

Erfan
  • 1,897
  • 13
  • 23
user3162506
  • 43
  • 1
  • 10
  • Do you mean a running average - i.e. the first result is the average of data(1:5), and the second the average of data(2:6), OR is the second result the average of data(6:10)? – Dave Sep 22 '16 at 11:45
  • I should have said in my last comment, if it is the first case, look at http://uk.mathworks.com/help/matlab/ref/filter.html which has this as the first worked example. If it is the second, then I'd suggest something like `mean(reshape(data,[],5),2);`, but data would need to be of a length that is a multiple of 5 for this to work. – Dave Sep 22 '16 at 11:54
  • @ Dave Yes..the first result is average of (1:5) and the second result is (6:10). and yes data should be of length multiple of 5 but it it's length is not multiple of 5 then the remaining points (for exp. 3 points are remaining out of 2985 in this case) can be appended to the result array as it is. – user3162506 Sep 22 '16 at 12:05
  • [`tsmovavg`](https://kr.mathworks.com/help/finance/tsmovavg.html) (Financial toolbox) – Jeon Sep 22 '16 at 12:12

1 Answers1

2

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.

Erfan
  • 1,897
  • 13
  • 23
  • can you tell me the meaning of this command, how it is working – user3162506 Sep 23 '16 at 12:25
  • [`numel`](http://de.mathworks.com/help/matlab/ref/numel.html), [`floor`](http://www.mathworks.com/help/matlab/ref/floor.html), [`reshape`](https://de.mathworks.com/help/matlab/ref/reshape.html), [`mean`](https://de.mathworks.com/help/matlab/ref/mean.html). You can start from most inner part, `numel(arr)`, and apply other functions to it step by step to see what is happening to the input in each step. – Erfan Sep 23 '16 at 12:48
  • Thanks. after some modifications, it worked. :) – user3162506 Sep 24 '16 at 07:10