Mean of elements of array

Hi,
I have an array of length 8000. I want to create another array by taking the mean of 10 elements at a time. I could do this using for loop. However, using for loop is time consuming and would like to know if there is any alternative for this.
Any help is highly appreciated.
array = rand(1,8000);
mean_array = zeros(1,800);
for i=1:800
mean_array(1,i) = mean(array(1,((i-1)*10+1):i*10));
end

2 Comments

Loops are often a slow way of performing tasks. Learn to write vectorized code instead, which is neater and faster:
Thanks Stephen !

Sign in to comment.

 Accepted Answer

mean_array = mean(reshape(array,10,[]));

1 Comment

Thanks James ! It saved lot of computation time. I have an extension of my previous question and would greatly appreciate if you could help me with it.
In my earlier question, I wanted to make an array by taking mean of 10 elements at a time. Is it possible to make an array by taking mean of various sizes of elements at a time ?
e.g., first element of mean_array is the mean of first 5 elements from original array. Second element of mean_array is the mean of next 8 elements from original array. Third element of mean_array is the mean of next 14 elements from original array and so on.
Thanks in advance !

Sign in to comment.

More Answers (0)

Categories

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

Asked:

on 7 Jan 2016

Commented:

on 7 Jan 2016

Community Treasure Hunt

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

Start Hunting!