Calculate daily values from cumulative values
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hello Matlab experts,
I'm trying to calculate daily values from given cumulative data. Cumulative data is saved in a .mat file. The data about COVID 19 pandemic.
It seems that this code is doing what it is supposed to, but I wonder if there is a better, more efficient way.
Thank you.
load ('cumul_variables.mat')
% Plot cumulative data for the state
dtv = datetime(dates, 'InputFormat','MM/dd/yy');
yyaxis left
bar (dtv, state_cases);
hold on
yyaxis right
plot(dtv,state_deaths);
set(get(gca(),'YAxis'),'Exponent',0,'TickLabelFormat','%0.f')
% Calculate daily values from cumulative data
state_cases_d = zeros(1,length(dates));
state_deaths_d = zeros(1,length(dates));
state_cases_d(1) = state_cases(1);
state_deaths_d(1) = state_deaths(1);
for i = 2:length(state_cases)
state_cases_d(i) = state_cases(i) - state_cases(i-1);
state_deaths_d(i) = state_deaths(i) - state_deaths(i-1);
end
% Plot daily data
figure(2)
yyaxis left
bar (dtv, state_cases_d);
hold on
yyaxis right
plot(dtv,state_deaths_d);
set(get(gca(),'YAxis'),'Exponent',0,'TickLabelFormat','%0.f')
3 comentarios
Voss
el 7 de Mayo de 2022
@Askic V I believe those expressions are in error. See my answer for a simpler (and correct) method.
load ('cumul_variables.mat')
state_cases_d_1 = [state_cases(1) -diff(state_cases(1:length(state_cases)-1))]; % erroneous expression
state_cases_d_2 = [state_cases(1) diff(state_cases)]; % intended expression (correct)
state_cases_d_3 = diff([0 state_cases]); % simpler expression (also correct)
isequal(state_cases_d_1,state_cases_d_2)
isequal(state_cases_d_2,state_cases_d_3)
Respuesta aceptada
Voss
el 7 de Mayo de 2022
You can simplify your calculations of state_cases_d and state_deaths_d by using the diff function:
load ('cumul_variables.mat')
% Plot cumulative data for the state
dtv = datetime(dates, 'InputFormat','MM/dd/yy');
yyaxis left
bar (dtv, state_cases);
hold on
yyaxis right
plot(dtv,state_deaths);
set(get(gca(),'YAxis'),'Exponent',0,'TickLabelFormat','%.0f')
% Calculate daily values from cumulative data
state_cases_d = diff([0 state_cases]);
state_deaths_d = diff([0 state_deaths]);
% Plot daily data
figure(2)
yyaxis left
bar (dtv, state_cases_d);
hold on
yyaxis right
plot(dtv,state_deaths_d);
set(get(gca(),'YAxis'),'Exponent',0,'TickLabelFormat','%.0f')
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Historical Contests en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!