nonZeroIndices = find(A);
breakIndices = [0 find(diff(nonZeroIndices) > 1)];
for ii = 1:numel(breakIndices)
if ii ~= numel(breakIndices)
c{ii,:} = A(nonZeroIndices(breakIndices(ii)+1) : nonZeroIndices(breakIndices(ii+1)));
else
c{ii} = A(nonZeroIndices(breakIndices(ii)+1):end);
end
disp(c{ii})
end
运行它,您将获得所需的输出:
1 7 3 4
1 4 5 3 2 4
2 4 3 10 3 5 3 2 1
1
这是一种没有循环的方法:
A = [1 7 3 4 0 0 0 0 0 0 1 4 5 3 2 4 0 0 0 0 0 0 0 2 4 3 10 3 5 3 2 1]; %// data
nz = logical(A); %// logical index of nonzeros of A
ind = find(conv(2*([false nz])-1,[1 -1],'valid')==2); %// find ends of runs of zeros
B = zeros(size(A)); B(ind) = 1; B = cumsum(B); %// integer label for each group
result = accumarray(B(nz).', A(nz).', [], @(x){x.'}); %'// nonzero elements by group
3 回答
如果你想让结果成为矩阵......你不能 . 如图所示,矩阵不能包含空元素 . 您可以做的最好的是单元格数组,其中单元格的每个元素对应于“矩阵”中的一行 .
首先,我们可以找到没有零的所有位置:
很明显,"runs"的索引对应于
A
中存在非零的位置 . 也就是说,某些索引n
和n-1
之间的差异是1.让我们使用diff
来查找描述:非一个值对应于运行中的那些“中断”发生的位置 . 让我们找到那些指数..
所以
A(nonZeroIndices(1:4))
,A(nonZeroIndices(5:10))
和A(nonZeroIndices(11:end))
对应于我们想要的3 "rows" . 请注意,这些索引中的每一个都对应于运行的结束,因此我将为它添加0以使for
循环更易于使用 .这是我的最终解决方案:
运行它,您将获得所需的输出:
这是一种没有循环的方法:
结果是行向量的单元阵列 . 在你的例子中,
您想要的输出似乎不是矢量,而是三个单独的矢量 . 我假设你想要它们作为单元格数组的单独单元格(
c{1}
,c{2}
和c{3}
)c
: