Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在MATLAB中拆分数组_Matlab_Split - Fatal编程技术网

在MATLAB中拆分数组

在MATLAB中拆分数组,matlab,split,Matlab,Split,我有一个整数数组,我想在0出现的地方拆分这个数组,并用一个函数给我拆分点 示例:数组:0 0 1 2 4 5 6 0 0 0 0 22 4 5 6 6 0 0 0 0 4 4 0 函数必须返回以下数字: [ 3 10 ;14 20 ;22 25 ] 这些数字是非零数字开始和结束的索引。试试这个 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 bec

我有一个整数数组,我想在0出现的地方拆分这个数组,并用一个函数给我拆分点

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

函数必须返回以下数字:

[ 3 10 ;14 20 ;22 25 ]
这些数字是非零数字开始和结束的索引。

试试这个

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);

下面是一个简单的矢量化解决方案,使用函数和:


关于主题,但略有变化:

>>> 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
已经指出的与
索引相关的位置语义,我只想补充一点,使用此解决方案,在计算
索引时,可以非常直接地处理各种方案。因此,应你的要求:

>>> 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

@amro-这更像是OP试图找到非零值孤岛的问题的倒数。@Kev:要转换为另一个,只需添加
array=(array==0)
在开始时(或者从另一个角度看,
array~=0
,这取决于你看它的方式).@amro-true,但它不是一个“精确”的重复项。@Kev:我想我应该称它为
重复答案
,而不是
重复问题
:)相关问题:
>>> 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
>>> 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