MATLAB: Applying the Consolidator function in a loop over a specified interval of a vector

consolidatorintervaliterationlooploop over a vector interval

Matlab beginner here…
I have a time series ("d41", 3335 elements). d41's values correspond with integer-hours of the day ("hourall", 3335 elements, e.g., 1, 2, 3, … 23). The Consolidator function should average all values of d41 corresponding with each integer hourall value. This is what I want to achieve, but only applying it to 240 values of d41 and hourall at a time for each iteration of a loop is proving problematic. Is my for statement not specifying an interval to be repeated through the length of the vector? Code below:
for i=1:240:length(d41);
[hourallC,d41C]=consolidator(hourall(i), d41(i), 'nanmean', 0);
end

Best Answer

My understanding is that you want to use the Consolidator function to average all of the d41 values but 240 at a time, i.e. 1-240, 241-280 etc.
The reason that you are not able to do that is because the for statement needs to be implemented in a different way.
When you execute a for loop like:
for i=1:10:100
i
end
The output of this code will be
>> i =
1,11,21,31,41,51,61,71,81,91
Having said that, to achieve the functionality you want you should either the for loop or the way you choose the indices for ‘hourall’ and ‘d41’.
So, instead of calling consolidator and using ‘hourall(i)’ as an input, you should use ‘hourall(i:240+i-1)’. The same would apply for the ‘d41’ vector. This will allow you to take 240-element chunks every loop repetition.
I would also suggest using a simple for loop as the one above and try to print the indices I mentioned so you can see how these change with every loop.