2

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

gabboshow
  • 5,359
  • 12
  • 48
  • 98

1 Answers1

3

To count your groups, a fast vectorized method using logical indexing is:

count = sum(diff([A 0]==0)==1)

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:

a0 = (A~=0);
d = diff(a0);
start = find([a0(1) d]==1)           % Start index of each group
len = find([d -a0(end)]==-1)-start+1 % Length, number of indexes in each group

In your case it might make sense to replace len with

finish = find([d -a0(end)]==-1) % Last index of each group

The length of start, len, and finish should be the same as the value of count so you could just use this if you need to do the breaking up. You can then use start and len (or finish) to store your groups in a cell array or struct or some other ragged array. For example:

count = length(start);
B = cell(count,1);
for i = 1:count
    B{i} = A(start(i):finish(i));
end
Community
  • 1
  • 1
horchler
  • 18,384
  • 4
  • 37
  • 73
  • thanks! and is there as well a way to split them in a fast way? My real vector contains up to 10000 elements... – gabboshow Jul 25 '13 at 23:42
  • ok I'll have a look and eventually ask a separate question thanks! ps yes this calculation is inside a for loop... – gabboshow Jul 25 '13 at 23:54
  • @gabboshow: I see that you kind of did ask about breaking into groups too so I've edited my answer to add that part. – horchler Jul 26 '13 at 00:04
  • @gabboshow: Great. Sorry about the initial misunderstanding of the question. Things move too fast around here. – horchler Jul 26 '13 at 00:34