arrays - Count elements containing less than 3 consecutive zeros within vector in Matlab -
for example, have 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 represents value @ every second. want count elements containing less 3 consecutive zeros in => obtain duration values in seconds a.
in case, counting stops before every 3 consecutive zeros , starts on after 3 consecutive zeros, , on. it's 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 this:
duration = [6 7 12]; in seconds
anyone got idea?
you can convert a
characters '0'
, '1'
(for example) depending on whether original value 0 or nonzero, use strsplit
, obtain number of elements of each substring.
let n = 3
number of zeros splitting. then:
duration = cellfun(@numel, strsplit(char((a>0)+'0'), repmat('0',1,n)));
note above code splitting based on exactly n
zeros. example, a = [1 2 3 0 0 0 0 4 5]
gives duration = [3 3]
, because fourth 0 assigned second substring.
if want split based on n
or more zeros, use regular expression:
duration = cellfun(@numel, regexp(char((a>0)+'0'), [repmat('0',1,n) '+'], 'split'));
for a = [1 2 3 0 0 0 0 4 5]
gives duration = [3 2]
.
Comments
Post a Comment