【发布时间】:2014-11-20 14:25:25
【问题描述】:
考虑以下矩阵,其中第一列是索引,第二列 - 是值,第三列 - 是索引更改后重置的累积和:
1 1 1 % 1
1 2 3 % 1+2
1 3 6 % 3+3
2 4 4 % 4
2 5 9 % 4+5
3 6 6 % 6
3 7 13 % 6+7
3 8 21 % 13+8
3 9 30 % 21+9
4 10 10 % 10
4 11 21 % 10+11
如何获得第三列避免循环?
我尝试以下方法:
A = [1 1;... % Input
1 2;...
1 3;...
2 4;...
2 5;...
3 6;...
3 7;...
3 8;...
3 9;...
4 10;...
4 11];
CS = cumsum(A(:,2)); % cumulative sum over the second column
I = [diff(data(:,1));0]; % indicate the row before the index (the first column)
% changes
offset=CS.*I; % extract the last value of cumulative sum for a given
% index
offset(end)=[]; offset=[0; offset] %roll offset 1 step forward
[A, CS, offset]
结果是:
ans =
1 1 1 0
1 2 3 0
1 3 6 0
2 4 10 6
2 5 15 0
3 6 21 15
3 7 28 0
3 8 36 0
3 9 45 0
4 10 55 45
4 11 66 0
如果有一种简单的方法可以将上面矩阵的第四列转换为
O =
0
0
0
6
6
15
15
15
15
45
45
因为 CS-O 给出了想要的输出。
如果有任何建议,我将不胜感激。
【问题讨论】:
-
有趣的问题,它显示了努力:+1
标签: matlab cumulative-sum