假设你有一个矩阵:
0 0 0 .... 0
A 0 0 .... 0
B 0 0 .... 0
C 0 0 .... 0
0 0 0 .... 0
D 0 0 .... 0
E 0 0 .... 0
Run Code Online (Sandbox Code Playgroud)
如果我想获得一个带有输出的新数组:
[A+B+C D+E]
Run Code Online (Sandbox Code Playgroud)
你会怎么做?当然我总是可以做循环并检查0,但我想知道是否还有其他选择.
使用cumsum生成分组值的向量,然后accumarray做的款项:
x = [0; 1; 2; 4; 0; 7; 3];
result = accumarray(cumsum(x==0) + (x(1)~=0), x);
Run Code Online (Sandbox Code Playgroud)
给
result =
7
10
Run Code Online (Sandbox Code Playgroud)
+ (x(1)~=0)如果x 不能以零开头,那么该部分是必要的.这部分确保了
x = [1; 2; 4; 0; 7; 3];
Run Code Online (Sandbox Code Playgroud)
结果是理想的
result =
7
10
Run Code Online (Sandbox Code Playgroud)
通过上述方法,每个零 开始一个新组.因此对于
x = [0; 1; 2; 4; 0; 7; 3; 0; 0; 5; 0];
Run Code Online (Sandbox Code Playgroud)
结果是
result =
7
10
0
5
0
Run Code Online (Sandbox Code Playgroud)
如果您希望每次运行一个或多个零来启动新组:首先折叠连续的零x,然后应用上述:
x = [0; 1; 2; 4; 0; 7; 3; 0; 0; 5; 0];
ind = [true; x(2:end)~=0 | x(1:end-1)~=0]; % index to remove a zero if preceded by zero
t = x(ind);
result = accumarray(cumsum(t==0) + (x(1)~=0), t);
Run Code Online (Sandbox Code Playgroud)
给
result =
7
10
5
0
Run Code Online (Sandbox Code Playgroud)