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 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Caesar Hernandez
am 30 Apr. 2020
Kommentiert: Shahnil Sadiq Noorani
am 30 Apr. 2020
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?
1 Kommentar
Akzeptierte Antwort
Geoff Hayes
am 30 Apr. 2020
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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!