How to find average value of every 10 numbers within a set of numbers?
11 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(1 个)
Cris LaPierre
2020-9-27
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!