在MATLAB中如何分割一个数组

9

我有一个整数数组,想要在0出现的地方将其分割,并需要一个能够给我分割点的函数。

例如:数组:0 0 0 1 2 4 5 6 6 0 0 0 0 0 22 4 5 6 6 0 0 0 4 4 0

该函数必须返回以下数字:

[ 3 10 ;14 20 ;22 25 ]

这些数字是非零数的起始和结束索引。

@amro - 这更像是那个问题的反向,其中 OP 正试图找到非零值的岛屿。 - Kev
@Kev: 要转换成另一个数组,只需在开头添加 array = (array==0);(或者反过来的 array~=0,取决于你从哪个角度看它)就行了... - Amro
@amro - 是的,但它不是一个“完全相同”的副本。 - Kev
@Kev:我想我应该把它称为“重复答案”,而不是“重复问题” :) - Amro
3个回答

5
这里有一个简单的向量化解决方案,使用函数DIFFFIND
>> array = [0 0 0 1 2 4 5 6 6 0 0 0 0 0 22 4 5 6 6 0 0 0 4 4 0];  %# Sample array
>> edgeArray = diff([0; (array(:) ~= 0); 0]);
>> indices = [find(edgeArray > 0)-1 find(edgeArray < 0)]

indices =

     3    10
    14    20
    22    25

上述代码首先创建一个列数组,其中包含指示非零元素的1,用零填充此数组(以防任何非零跨度延伸到数组边缘),并进行逐元素差分。这会生成一个向量edgeArray,其中1表示非零跨度的开始,-1表示非零跨度的结束。然后使用函数FIND获取开始和结束的索引。
一点小细节:这些不是像你所说的非零跨度的起点和终点的索引。它们实际上是非零跨度起点之前和终点之后的索引。您可能实际上需要以下内容:
>> indices = [find(edgeArray > 0) find(edgeArray < 0)-1]

indices =

     4     9
    15    19
    23    24

2

试试这个

a = [0 0 0 1 2 4 5 6 6 0 0 0 0 0 22 4 5 6 6 0 0 0 4 4 0];

%#Places where value was zero and then became non-zero
logicalOn = a(1:end-1)==0 & a(2:end)~=0;

%#Places where value was non-zero and then became zero
logicalOff = a(1:end-1)~=0 & a(2:end)==0;

%#Build a matrix to store the results
M = zeros(sum(logicalOn),2);

%#Indices where value was zero and then became non-zero
[~,indOn] = find(logicalOn);

%#Indices where value was non-zero and then became zero
[~,indOff] = find(logicalOff);

%#We're looking for the zero AFTER the transition happened
indOff = indOff + 1;

%#Fill the matrix with results
M(:,1) = indOn(:);
M(:,2) = indOff(:);

%#Display result
disp(M);

2

关于主题,但稍有变化:

>>> a= [0 0 0 1 2 4 5 6 6 0 0 0 0 0 22 4 5 6 6 0 0 0 4 4 0];
>>> adjust= [0 1]';
>>> tmp= reshape(find([0 diff(a== 0)])', 2, [])
tmp =
    4   15   23
   10   20   25
>>> indices= (tmp- repmat(adjust, 1, size(tmp, 2)))'
indices =
    4    9
   15   19
   23   24

正如gnovice在与indices相关的位置语义方面已经指出的那样,我补充说明,通过这种解决方案,可以非常简单地处理各种方案,计算indices。因此,针对您的请求:
>>> adjust= [1 0]';
>>> tmp= reshape(find([0 diff(a== 0)])', 2, []);
>>> indices= (tmp- repmat(adjust, 1, size(tmp, 2)))'
indices =
    3   10
   14   20
   22   25

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接