Create loop over time period adding iteratively days
2 views (last 30 days)
Show older comments
Dear community,
I have a question regarding a simulation I try to run over 200days for a dataset over a time period. I start at time=0 and want to add always a day more (1st day=0 and day=1, then day=0, day=1 and day=2 and so on; so always calculating my average values from time=0). The problem is that my loop so far is not providing the "steps" for each day right now. How can I solve this? Any hints? Right now I just get 200 times the same results... Thank you very much!
This is what I have:
startDate = min(data.DATE);
endDate = max(data.DATE);
d = [startDate; endDate];
iteration = 0;
while iteration <=200
for k=1:numel(d)
size(data);
n = size(data,1);
avg_value_total = groupsummary(data,'group', 'mean', 'POS_WERT');
iteration = iteration+1;
disp( ['number of loop:' num2str(iteration)])
end
end
0 Comments
Answers (1)
Harsh Mahalwar
on 8 Mar 2024
Hi,
From what I can gather, you are trying to modify the loop to correctly increment the date range by one day with each iteration, ensuring unique calculations for each of the 200 days.
“Right now I just get 200 times the same results”
As the current loop does not change the range of dates (d) that is being used to calculate averages over; remains [startDate; endDate] throughout the entire loop. This is why you're getting the same result 200 times.
To solve this, adjust the loop to dynamically change the date range for calculating averages over, based on the iteration number. Here's a revised code that incorporates these changes:
startDate = min(data.DATE);
endDate = max(data.DATE);
iteration = 0;
while iteration <= 200 && currentDate <= endDate
% Calculate the current end date for the iteration
currentDate = startDate + days(iteration);
% Filter data to only include rows up to the current date
filteredData = data(data.DATE <= currentDate, :);
% Calculate the average values for the filtered dataset
avg_value_total = groupsummary(filteredData, 'group', 'mean', 'POS_WERT');
disp(['Number of loop: ' num2str(iteration)]);
% Increment the iteration count
iteration = iteration + 1;
end
(Note: This code assumes that data.DATE is of datetime type. If it's not, you will need to convert it accordingly.)
I hope this helps, thanks!
0 Comments
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!