Cumulative sum with multiple constraints

1 回表示 (過去 30 日間)
Dixi
Dixi 2019 年 6 月 25 日
回答済み: Dixi 2019 年 6 月 25 日
Hello,
i'm trying to calculate a cumulative sum (of column value) in a table with two constraints in different columns (date, time).
The cumulative sum should add all values for equal dates and timesteps. The amount of values per date and timestep might be variable.
date = [20190101; 20190101; 20190101; 20190101; 20190101; 20190101; 20190101; 20190102; 20190102; 20190102; 20190102; 20190102];
time = [0; 0; 0; 0; 12; 12; 12; 0; 0; 12; 12; 12];
value = [2; 7; 5; 3; 5; 4; 1; 6; 8; 2; 5; 8];
T = table (date, time, value);
The cumulative sum in the fourth column of the table should be like:
csum = [2; 9; 14; 17; 5; 9; 10; 6; 14; 2; 7; 15]
Thanks!

採用された回答

Kaustav Bhattacharya
Kaustav Bhattacharya 2019 年 6 月 25 日
start = 0;
cumulativesum = zeros(height(T),1);
for row = 1:height(T)
if row == 1
cumulativesum(row) = T.value(row);
start = 1;
elseif T.date(row-1) == T.date(row) && T.time(row-1) == T.time(row)
cumulativesum(row) = sum(T.value(start:row));
else
start = row;
cumulativesum(row) = T.value(row);
end
end
'cumulativesum' gives you the result you were looking for.

その他の回答 (2 件)

Prasanth Sikakollu
Prasanth Sikakollu 2019 年 6 月 25 日
You can try the following code to get the cumulative sum as fourth column in table T.
date = [20190101; 20190101; 20190101; 20190101; 20190101; 20190101; 20190101; 20190102; 20190102; 20190102; 20190102; 20190102];
time = [0; 0; 0; 0; 12; 12; 12; 0; 0; 12; 12; 12];
value = [2; 7; 5; 3; 5; 4; 1; 6; 8; 2; 5; 8];
csum = [value(1)] % Initialising the array with value(1)
cur_time = time(1) % Initialising the current time with time(1)
for i = 2:length(value)
if cur_time == time(i)
csum = [csum ; csum(i-1) + value(i)] % finds csum if time(i) is same as cur_time and appends it at the end of csum
else
cur_time = time(i)
csum = [csum ; value(i)] % updates the cur_time and appends value(i) at the end of csum
end
end
T = table (date, time, value, csum);
Hope this helps in solving your problem

Dixi
Dixi 2019 年 6 月 25 日
Both answers are working fine.
Thank you!

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by