Acquire annual data from table
1 view (last 30 days)
Show older comments
Florian van der Stap
on 16 Dec 2021
Commented: Adam Danz
on 17 Dec 2021
I am trying to calculate the annual cumulative freezing degree days from a dataset with air temperature observations. I came up with the below code, but the code 1) skips the final observation for each year and 2) the row index exceeds the table dimension. How can I better get the value for each year? And additionally is it also possible to get a value when the year is defined from july to june? I am using R2021b
T = readtable('RaaheNahkiainen.csv'); % skips the first row of data
T_f = -0.3; % freezing temperature
CFDD = zeros(T.Year(end) - T.Year(1) + 1,1); % annual cumulative freezing degree days to be filled
i = 2;
for j = 1:(T{end,1} - T{1,1} + 1)
while T{i,1} == T{i-1,1}
if T{i,6} < T_f
CFDD(j) = CFDD(j) + (T_f - T{i,6}) % add freezing degree days if temp is below freezing temperature
else
CFDD(j) = CFDD(j);
end
i = i + 1;
end
i = i + 1;
end
Thank you for your time!
2 Comments
Accepted Answer
Adam Danz
on 16 Dec 2021
Edited: Adam Danz
on 16 Dec 2021
Convert your table to a timetable,
T = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/836120/RaaheNahkiainen.csv');
head(T) % Show sample
dtm = datetime(T.Year, T.m, T.d); % Create datetime vector
TT = [timetable(dtm), T(:,5:end)]; % Create timetable
head(TT) % Show sample
Now apply retime to compute anual averages. Only pass numeric columns to retime.
isNumericColumn = varfun(@isnumeric, TT, 'OutputFormat','uniform');
TTavg = retime(TT(:,isNumericColumn),'yearly','mean')
5 Comments
Adam Danz
on 17 Dec 2021
> When I use T.FDD it does not work, since I get the error: All input arguments must be tables.
My bad. What I meant to suggest is instead of using numeric column indexing, use the name of the column if the name is known in advanced. For example, instead of T(:,8), use T(:,'FDD') where FDD is column 8. Table indexing using variable names is safer because the order of columns can change in a table.
Regarding your second question, it sounds like you just need to used indexing. Use month to return the month number for each datetime value and then use ismember to determine which elements of the datetime vector are within your list of months.
Example:
dtm = datetime(1999,01,01) + days(1:15:1000)'
desiredMonths = [7 8 9];
isDesiredMonth = ismember(month(dtm), desiredMonths)
Now you can use the logical vector isDeisredMonth to isolate rows of your table that are within your list of desired months.
More Answers (0)
See Also
Categories
Find more on Tables 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!