Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count elements containing less than 3 consecutive zeros within vector in Matlab

Tags:

arrays

matlab

For example, I have the following vector:

A = [34 35 36 0 78 79 0 0 0 80 81 82 84 85 86 102 0 0 0 103 104 105 106 0 0 107 201 0 202 203 204];

Each element within A represents a value at every second. I want to count the elements containing less than 3 consecutive zeros in A => I will obtain duration values in seconds for A.

In this case, the counting stops before every 3 consecutive zeros and starts over after the 3 consecutive zeros, and so on. It's like this:

A = [34->1s 35->2s 36->3s 0->4s 78->5s 79->6s stop 80->1s 81->2s 82->3s 84->4s 85->5s 86->6s 102->7s stop 103->1s 104->2s 105->3s 106->4s 0->5s 0->6s 107->7s 201->8s 0->9s 202->10s 203->11s 204->12s];

The result would like this:

Duration = [6 7 12]; in seconds

Anyone got any idea?

like image 530
Bowecho Avatar asked Feb 09 '23 14:02

Bowecho


1 Answers

One approach with convolution -

%// Input
A = [0 0 0 0 0 0 0 34 35 36 0 78 79 0 0 0 ...
    80 81 82 84 85 86 102 0 0 0 103 104 105 106 0 0 107 201 0 202 203 204];

%// Mask with all >= groups of three consecutive 0's set at 0's, 1's elsewhere 
M = conv(double(conv(double(A==0),ones(1,3),'same')>=3),ones(1,3),'same')==0

%// Append with 0's to get their indices in the next step
dfd = diff([0 M 0])

%// Get indices for falling and rising edges and subtract them for Duration
Duration = find(dfd==-1) - find(dfd==1)

Sample run -

>> A
A =
  Columns 1 through 14
     0     0     0     0     0     0     0    34    35    36     0    78    79     0
  Columns 15 through 28
     0     0    80    81    82    84    85    86   102     0     0     0   103   104
  Columns 29 through 38
   105   106     0     0   107   201     0   202   203   204
>> M
M =
  Columns 1 through 14
     0     0     0     0     0     0     0     1     1     1     1     1     1     0
  Columns 15 through 28
     0     0     1     1     1     1     1     1     1     0     0     0     1     1
  Columns 29 through 38
     1     1     1     1     1     1     1     1     1     1
>> Duration
Duration =
     6     7    12
like image 185
Divakar Avatar answered Feb 15 '23 09:02

Divakar