How do I make a for loop that averages the first 150 values of vector, x, saves it, and then averages the next 150 values of the same vector, x, saves it, and continues for the entirety of the vector, x.
2 次查看(过去 30 天)
显示 更早的评论
I have a column vector, x, in which every 150 elements need to be averaged and the result saved, as a new vector, y. So far I have:
for i = x(1:150:length(x))
mean(i)
end
But I cannot figure out how to get the mean for the next 150 (151:300) and so on until the end. How should I adjust this code?
采纳的回答
Geoff Hayes
2020-4-30
Caesar - if you need to use a loop (as you have shown above) then you can set the step size to be 150 and try something like
for i = 1:150:length(x)
% calculate the mean with x(i:i+150-1)
end
This will work assuming that the length(x) is divisible by 150. If not, then you will need to update the code to account for that. Alternatively, you can reshape the array so that you have columns (or rows) of 150 elements each and then determine the mean of each column (or row). Again, if the length(x) is NOT divisible by 150 then you would need to handle the last few elements separately.
x = 1:1:450;
x = reshape(x,150,[]);
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!