How to find average value of every 10 numbers within a set of numbers?

14 views (last 30 days)
n=fix(length(speed)/10);
avgspeed = zeros(n,1);
for i=length(speed):-10:1
for j=cumsum(speed(i:i+9))/10
avgspeed(i) = j;
end
end
fprintf ('The average speed of every 10 elements is:')
disp (avgspeed)
When I run the script, this is the error I get.
>> average10speed
Index exceeds the number of array elements (452).
Error in average10speed (line 5)
for j=sum(speed(i:i+9))/10
The purpose of this code is to take a data set, and put it into pieces of 10, average them, so I can find the average of every 10 elements and then eventually plot that data. So I was hoping it would come out of the script as a vector, and not a display of each average as one number individually.
Here speed is a list of a lot of different amount of speeds on a run ranging from 0 to about 5m/s.
How can I get it to be put into one vector? so I can then plot it?

Answers (1)

Cris LaPierre
Cris LaPierre on 27 Sep 2020
The problem is how you set up your loops.
The first value of i is the length of speed, 452. The first value of j is trying to index the values i:i+9, or 452:461. Since that is indexing a value larger than the variable, it returns an error.
You might try
for i=length(speed):-10:1
j=cumsum(speed(i:max(i-9,1)))/10
end

Tags

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!