在MATLAB中拆分数组

时间:2011-07-01 14:53:42

标签: matlab split

我有一个整数数组,我想把这个数组拆分为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 ]

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

3 个答案:

答案 0 :(得分: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

上面的代码首先创建一个列数组,其中一个列表示非零元素,用零填充此数组(如果任何非零跨度延伸到数组边缘),并采用元素差异。这会给出一个向量edgeArray1表示非零跨度的开始,-1表示非零跨度的结束。然后函数FIND用于获取开始和结束的索引。

一方注意/挑剔:这些不是你所说的非零跨度开始和结束的指数。从技术上讲,它们是开始之前的指数之后非零跨度的结尾。您可能实际上想要以下内容:

>> indices = [find(edgeArray > 0) find(edgeArray < 0)-1]

indices =

     4     9
    15    19
    23    24

答案 1 :(得分: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 :(得分: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相关的位置语义,我只想补充一点,通过这个解决方案,在计算{{1}时,可以非常直接地处理各种方案。 }。因此,根据您的要求:

indices