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.

1 次查看(过去 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
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 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by