MATLAB: Multiplying by the number of the day of each month in a cell arrays

cell arraysMATLAB

Hey all,
I have a 1 x 8 cell which includes tables. In each table, there is the date column and the results column. In each row, I want to multiply results values by the number of days in the month from the date column (considering leap and non-leap years).
For example:
date results new_results
———- ————- —————
1989-01-01 0.2 31 * 0.2 = 6.2
1989-02-01 0.8 30 * 0.8 = 24
. . .
. . .
. . .
2018-12-01 0.4 31*0.4 = 12.4
I read matlab help and tried to use this code:
calculations = arrayfun(@(x) test{x}.results*days(test{x}.date));
But it not working and say not enough inputs.
I attached my data. Any help is highly appreciated.
Thank you !

Best Answer

Try this:
D = load('test.mat');
test = D.test;
T1 = test{1}; % Select Table #1 From 'test'
[yt,mt,dt] = ymd(T1.date); % Return: Year & Month

dim = eomday(yt,mt); % Return: Days In Month

new_results = T1.results .* dim; % Create: 'new_results' Variable (Column)new_results’ Variable (Column)
T1.new_results = new_results; % Concatenate

producing for example:
Check = T1(1:12,:)
Check =
12×6 table
model_name date lon lat results new_results
__________ __________ ___ ___ _______ ___________
{'ERA5_1'} 1989-01-01 43 40 0.22701 7.0373
{'ERA5_1'} 1989-02-01 43 40 0.66383 18.587
{'ERA5_1'} 1989-03-01 43 40 1.4266 44.225
{'ERA5_1'} 1989-04-01 43 40 1.9511 58.534
{'ERA5_1'} 1989-05-01 43 40 1.6575 51.382
{'ERA5_1'} 1989-06-01 43 40 1.3122 39.367
{'ERA5_1'} 1989-07-01 43 40 0.86207 26.724
{'ERA5_1'} 1989-08-01 43 40 0.6105 18.926
{'ERA5_1'} 1989-09-01 43 40 0.77049 23.115
{'ERA5_1'} 1989-10-01 43 40 2.9392 91.114
{'ERA5_1'} 1989-11-01 43 40 3.2634 97.901
{'ERA5_1'} 1989-12-01 43 40 0.9547 29.596
There is an error in the ‘example’ in the posted Question. February has 28 (or 29) days, never 30.
EDIT — (22 Mar 2020 at 14:13)
This can easily be extended to all the tables in ‘test’:
for k = 1:numel(test)
Tk = test{k}; % Select Table From ‘test’
VarEnd = numel(Tk.Properties.VariableNames) % Retrieve: ‘VariableNames’
[yt,mt,dt] = ymd(Tk.date); % Return: Year & Month
DIM = eomday(yt,mt); % Return: Days In Month
new_Val = Tk{:,VarEnd} .* DIM; % Create: ‘new_results’ Variable (Column)
Tk{:,VarEnd+1} = new_Val; % Concatenate
Tk.Properties.VariableNames{VarEnd+1} = ['new_' Tk.Properties.VariableNames{VarEnd}];
test{k} = Tk; % Save New Table To Previous Cell
end
The complexity arises because the last variable name in ‘test{1}’ is ‘results’ and in the rest it is ‘precip’. This accommodates every table regardless of what the last variable (column) name is.