MATLAB: Grouping continuous nonzero in a row vector

continuousgroupingnonzero

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!

Best Answer

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.