フィルターのクリア

Grouping continuous nonzero in a row vector

7 ビュー (過去 30 日間)
Mona Mahboob Kanafi
Mona Mahboob Kanafi 2013 年 11 月 1 日
回答済み: Emma DeWitt Cotter 2017 年 3 月 15 日
Dear All,
Is there any MATLAB function to ease grouping continuous nonzero elements of a row vector? I will explain further in the example below:
If I have such a simple row vector: A = [0,0,0,0,3,2,5,2,4,1,5,0,1,2,5,0,0,0,0,0,0,0,0,0,1,1,2,6,3,1]
Then I need to work on each continuous nonzero groups separately, i.e. I need to obtain matrices below to further analyze each group:
A1 = [3,2,5,2,4,1,5] ; A2 = [1,2,5] ; A3 = [3,2,5,2,4,1,5];
Thanks!

採用された回答

Cedric
Cedric 2013 年 11 月 1 日
編集済み: Cedric 2013 年 11 月 1 日
Here is one solution..
wrap = [0, A, 0] ;
temp = diff( wrap ~= 0 ) ;
blockStart = find( temp == 1 ) + 1 ;
blockEnd = find( temp == -1 ) ;
blocks = arrayfun( @(bId) wrap(blockStart(bId):blockEnd(bId)), ...
1:numel(blockStart), 'UniformOutput', false ) ;
With that, you get
>> blocks{1}
ans =
3 2 5 2 4 1 5
>> blocks{2}
ans =
1 2 5
>> blocks{3}
ans =
1 1 2 6 3 1
Another solution would be to compute the start and size of clusters of 0's, eliminate the latter from A, and MAT2CELL what remains using proper boundaries based on the aforementioned start and size information.
  2 件のコメント
Mona Mahboob Kanafi
Mona Mahboob Kanafi 2013 年 11 月 5 日
Thank you very much man!
Cedric
Cedric 2013 年 11 月 5 日
You're welcome.

サインインしてコメントする。

その他の回答 (3 件)

Andrei Bobrov
Andrei Bobrov 2013 年 11 月 5 日
編集済み: Andrei Bobrov 2013 年 11 月 6 日
A = [0,0,0,0,3,2,5,2,4,1,5,0,1,2,5,0,0,0,0,0,0,0,0,0,1,1,2,6,3,1];
ii = zeros(size(A));
jj = A > 0;
ii(strfind([0,jj(:)'],[0 1])) = 1;
idx = cumsum(ii).*jj;
out = accumarray( idx(jj)',A(jj)',[],@(x){x'});
  3 件のコメント
Andrei Bobrov
Andrei Bobrov 2013 年 11 月 6 日
Hi Mona! I corrected.
Mona Mahboob Kanafi
Mona Mahboob Kanafi 2013 年 11 月 6 日
Thankss a lot, quite clever!

サインインしてコメントする。


Akhlaqur Rahman
Akhlaqur Rahman 2017 年 1 月 9 日
y = [1 2 1 3 1 4 0 0 0 0 4 5 2 3 0 0 5 4 2 3 0 0 0 4 5 3];
y = padarray(y,[0,3]);
y1 = uint8(y>0);
k = 1;
j = 1;
for i = 1+1:length(y)-1
if y1(i)>0 && y(i-1)==0
x1(j) = i;
j = j+1;
elseif y1(i)==0 &&y1(i-1)>0
x2(k) = i;
k = k+1 ;
end
end
for i = 1:length(x1)-1
z{i}=y(x1(i):x2(i)-1);
cell2mat(z(i))
end

Emma DeWitt Cotter
Emma DeWitt Cotter 2017 年 3 月 15 日
This can also be achieved using the bwconncomp function if you have the Image Processing toolbox. The PixelIdxList field will be a cell containing the list of indices associated with each group of nonzero elements.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by