使用循环将累积和添加到 MATLAB 中的 table

Adding a cumulative sum to a table in MATLAB using a loop

我是 MATLAB 新手。对于 uni 项目,我有兴趣使用循环向现有 table 添加一列。出于说明目的,我使用下图来解释我的情况。

如图所示,在当前 table 中,A 列中有一些值(子类别的值),B 列中有一些值(类别的目标值)。我需要为 B 列的每个类别的子类别值创建一个累积总和的列,如所需的 table.

所示

我试图按以下方式使用 cumsum() 函数,但似乎不起作用。

for i = table.B(1):table.B(end)
    table.C(i)=cumsum(table.A(i))
end

我知道可能存在一些索引问题,但不知道如何解决这个问题。

这可以通过 unique to produce a vector of grouping indices, and accumarray 轻松完成,以计算每组的总和:

T = table([12; 15;18; 11; 20; 22; 26; 32; 35; 40; 25; 35], ...
          [60; 60; 60; 60; 75; 75; 75; 200; 200; 200; 200; 200], ...
          'VariableNames', {'A', 'B'}); % example data with columns 'A', 'B'
[~, ~, ind] = unique(T.B, 'stable'); % grouping indices
sums = accumarray(ind, T.A); % sum of each group
T.C = sums(ind); % build result column