How to calculate function for different parts of array with values of same lenght in one big array

4 views (last 30 days)
Can anyone help me solve this problem? I have for example this array of values: T =
40.9992
40.9992
44.3003
44.3003
41.0270
41.0270
41.2030
41.2030
43.1300
43.1300
44.6121
44.6121
41.6218
41.6218
41.3046
41.3046
44.5307
44.5307
47.1521
47.1521
45.7819
45.7819
41.7752
41.7752
42.7205
42.7205
42.2346
42.2346
42.1536
42.1536
41.0068
41.0068
43.9901
43.9901
and I would like to calculate mean (or another function) for each 5 values in the the array (therefore for 1:5, 6:10, 11:15 and so on.. till the end). Is it somehow possible do it in one command or loop that I will receive means for each block of values in one time/answer, eventually in table output. Thank you very much in advance.

Answers (1)

Guillaume
Guillaume on 20 Jul 2018
Assuming the number of elements in the vector is a multiple of 5, you can just reshape the array into a matrix of 5 rows and calculate the mean across the rows (the default), so:
mean(reshape(yourvector, 5, []))
If the number of elements is not a multiple of 5, then you need to explain what should happen for the few leftover elements.
  2 Comments
Jaroslav Krc
Jaroslav Krc on 25 Jul 2018
Thank you very much, it works :-), nice. All right, but if the number of values is not a multiple of 5, how the function would look like when we would like to have the mean also from leftovers? Is it somehow possible to implement this into one command/function? Thank you very much again. J.
Guillaume
Guillaume on 25 Jul 2018
The simplest way is to append NaN to the vector to make its length a multiple of 5, reshape it, then calculate the mean with the 'omitnan' option:
extendedvector = [yourvector; nan(mod(-numel(yourvector), 5), 1)]; %append as many nans as necessary to make length a multiple of 5
result = mean(reshape(extendedvector, 5, []), 'omitnan')

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!