I have a vector like this:
A = [1 2 1 1 1 4 5 0 0 1 2 0 2 3 2 2 2 0 0 0 0 33]
I would like to count how many GROUPS of non zero elements it contains and save them.
so I want to isolate:
[1 2 1 1 1 4 5]
[1 2]
[2 3 2 2 2]
[33]
and then count the groups (they should be 4) :)
Can you help me please?
Thanks
To count your groups, a fast vectorized method using logical indexing is:
This assumes that
A
is a row vector as in your example. This works with no zeros, all zeros, the empty vector, and several other test cases I tried.To obtain your groups of values themselves, you can use a variation to my answer to a similar question:
In your case it might make sense to replace
len
withThe
length
ofstart
,len
, andfinish
should be the same as the value ofcount
so you could just use this if you need to do the breaking up. You can then usestart
andlen
(orfinish
) to store your groups in a cell array or struct or some other ragged array. For example: