How to add data stored in structure depending on other data related but stored in a different structure
2 views (last 30 days)
Show older comments
Hi people!
I have some streamflow data that are stored in a structure called 'debit' (1x78888). Each streamflow data are related to a date and time (dd-MM-yyyy HH:mm:ss), which are stored in an other structure called 'Date' (1x78888). I want to have a mean streamflow per day. So what I did, is that I copied all the dates but without the hours to have data like 'dd-MM-yyyy'. Then I tried to do a while loop to sum all streams for a same day.
So far, my script looks like bellow, but it doesn't works. All I have in my structure called 'debit_total' are zeros...
Can someone help me with this ?
I hope it is clear enough !
load DE5.mat;
debit = Data.raw.horaire.debits;
date = Data.raw.horaire.time;
date.Format = 'dd-MMM-yyyy';
date_jour = date;
debit_total = zeros(size(debit));
i = 1;
while i <= length(date_jour)
if date_jour(i) == date_jour(i+1)
debit_total(i) = debit(i) + debit(i+1);
debit_total(i+1) = debit(i) + debit(i+1);
end
i = i + 1;
end
1 Comment
Stephen23
on 9 Jun 2023
Use MATLAB functions, rather than renventing everything yourself. Store the data in a table, then use one of these:
Accepted Answer
chicken vector
on 2 Jun 2023
Edited: chicken vector
on 2 Jun 2023
I am not sure I udnerstand correctly what you need, because this line is confusing me:
debit_total = zeros(size(debit));
You want the average per day but you initialise the output with the same number of elements of every time instant.
Is something like this close to what you are looking for?
% Create fictitious data:
N = 5e3;
totDays = 40;
debit = randi(1e2, 1, N);
date = linspace(datetime('now'), ...
(datetime('now') + days(totDays)), ...
N) - years(1);
% Find of unique dates:
[y, m, d] = ymd(date);
[~, idx] = unique([y', m', d'], 'Rows', 'Stable');
uniqueDays = date(idx);
% Loop over each unique day:
meanDebit = zeros(size(uniqueDays));
for j = 1 : length(uniqueDays)
% Find all debits corresponding to the same [day, month, year]_
meanDebit(j) = mean(debit( day(date) == day(uniqueDays(j)) ...
& month(date) == month(uniqueDays(j)) ...
& year(date) == year(uniqueDays(j)) ));
% If timespan is less than a year you can compare only days and months:
% meanDebit(j) = mean(debit( day(date) == day(uniqueDays(j)) ...
% & month(date) == month(uniqueDays(j)) );
% If timespan is less than a month you can compre only days:
% meanDebit(j) = mean(debit( day(date) == day(uniqueDays(j)) ));
end
% Display result:
uniqueDays.Format = 'dd-MMM-yyyy';
table(uniqueDays', meanDebit', 'VariableNames', {'Date', 'Average Debit'})
More Answers (0)
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!