例如,我有以下向量:
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];
A中的每个元素代表每秒的值。我想计算A =>中包含少于3个连续零的元素。我将以秒为单位获得持续时间值A.
在这种情况下,计数在每3个连续零之前停止,并在3个连续的零之后重新开始,依此类推。就像这样:
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];
结果是这样的:
Duration = [6 7 12]; in seconds
有人有任何想法吗?
答案 0 :(得分:3)
使用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)
示例运行 -
>> 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
答案 1 :(得分:2)
您可以将A
转换为字符'0'
和'1'
(例如),具体取决于原始值是零还是非零,使用strsplit
然后获取数字每个子串的元素。
设N = 3
为分割的零数。然后:
Duration = cellfun(@numel, strsplit(char((A>0)+'0'), repmat('0',1,N)));
请注意,上面的代码基于完全N
零进行拆分。例如,A = [1 2 3 0 0 0 0 4 5]
给出Duration = [3 3]
,因为第四个零被分配给第二个子字符串。
如果您想基于 N
或更多零进行拆分,请使用正则表达式:
Duration = cellfun(@numel, regexp(char((A>0)+'0'), [repmat('0',1,N) '+'], 'split'));
对于A = [1 2 3 0 0 0 0 4 5]
,这会给Duration = [3 2]
。
答案 2 :(得分:2)
这是另一个基于矢量化conv
的替代方案:
Duration = diff([0,find(~conv(A, ones(1,3))),numel(A)+3])-3
答案 3 :(得分:1)
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];
count=0;
count2=0;
Duration = [];
for i=1:(size(A,2)-3)
count2=count2+1;
if(A(1,i+1)==0)
count=count+1;
if(A(1,i+2)==0)
count=count+1;
else
count=0;
end
if(A(1,i+3)==0)
count=count+1;
else
count=0;
end
if(count==3)
Duration = [Duration,count2 ];
count2=-3;
end
else
count=0;
end
end
Duration = [Duration,count2+3 ];
Duration
代码检测到3个连续的零,第二个计数器跟踪持续时间。我希望这会有所帮助。
答案 4 :(得分:0)
如果您漫游到Fileexchange并抓取seqle,您可以使用它来提取所有零和非零元素的运行,从而简化您的搜索。