算在Matlab载体内含有连续少于3个零元素 [英] Count elements containing less than 3 consecutive zeros within vector in Matlab
问题描述
例如,我有以下矢量:
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];
一个再$ P $中的每个元素psents在每一秒的值。我想算包含在连续的不到3个零元素=>我会为A.秒获得持续时间值
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.
在这种情况下,计数每3个连续的零之前停止和3的连续零后重新开始,依此类推。它是这样的:
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?
推荐答案
您可以 A
转换为字符 0
和 1
(例如)根据原始值是否为零或非零,使用 strsplit
和然后获得每个子的元素的数量。
You can convert A
to characters '0'
and '1'
(for example) depending on whether the original value is zero or nonzero, use strsplit
and then obtain the number of elements of each substring.
让 N = 3
是零用于分割的数量。然后:
Let N = 3
be the number of zeros for splitting. Then:
Duration = cellfun(@numel, strsplit(char((A>0)+'0'), repmat('0',1,N)));
请注意,上面的code确实根据的究竟 N
零分裂。例如, A = [1 2 3 0 0 0 0 4 5]
给持续时间= [3 3]
,由于第四零被分配给第二子
Note that the above code does the splitting based on exactly N
zeros. For example, A = [1 2 3 0 0 0 0 4 5]
gives Duration = [3 3]
, because the fourth zero is assigned to the second substring.
如果您想根据 N
以上零分割,使用常规的前pression:
If you want to split based on N
or more zeros, use a regular expression:
Duration = cellfun(@numel, regexp(char((A>0)+'0'), [repmat('0',1,N) '+'], 'split'));
有关 A = [1 2 3 0 0 0 0 4 5]
这给了持续时间= [3 2]
。
这篇关于算在Matlab载体内含有连续少于3个零元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!