我想在具有最短宽度的矢量中找到零峰值,即具有单个样本非零且相邻样本为零的峰值,即[0 ~0 0]
具有~0
峰值.示例:if x = [1 0 2 0 0 3 0 4 5 6 0 7 0 8]
,然后我想找到2,3和7并将它们设为0,即x
变为[1 0 0 0 0 0 0 4 5 6 0 0 0 8]
.下面的代码可以解决这个问题,但有更高效或更好的方法可以做到这一点,还是存在一个在向量(甚至矩阵)中找到某种模式的Matlab函数?
% remove peaks of shape [0 ~0 0]
k = find(x);
for j=k'
if j==numel(x) || j==1
elseif ~x(j-1) && ~x(j+1)
x(j) = 0;
end
end
Run Code Online (Sandbox Code Playgroud)
您正在寻找与内核的卷积与[1,1,1]
原始卷积不同的元素.唯一的复杂因素是我们必须忽略边缘情况:
x = [1 0 2 0 0 3 0 4 5 6 0 7 0 8];
y = conv(x,[1,1,1],'same');
ind = find(x==y);
x(ind(2:end-1)) = 0
Run Code Online (Sandbox Code Playgroud)
要么
x(find(x(2:end-1)==conv(x,[1,1,1],'valid'))+1) = 0
Run Code Online (Sandbox Code Playgroud)
如果面对正面和负面数字的前景,那么根据Craigim在评论中的建议:
xx = abs(x);
x(find(xx(2:end-1)==conv(xx,[1,1,1],'valid'))+1) = 0
Run Code Online (Sandbox Code Playgroud)
使用conv
(按照Dan的答案)可能是最好的方法; 但它也可以用strfind
:
x(strfind(x~=0, [0 1 0]) + 1) = 0;
Run Code Online (Sandbox Code Playgroud)
或者diff
用于计算二阶差异:
x(find(diff(~x, 2)==2) + 1) = 0;
Run Code Online (Sandbox Code Playgroud)
这将是我的方式来做到这一点
x_add = x(1:end-2) + x(2:end-1) + x(3:end);
x(find([0,x(2:end-1)==x_add,0]))=0;
Run Code Online (Sandbox Code Playgroud)
它会为每个值添加先前的值和下一个值,并检查哪个值没有更改