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!