我试图切断输入数组的前导和/或尾随零点,这些输入数组可能有,也可能没有。我看到了以下问题的答案:
MATLAB - Remove Leading and Trailing Zeros From a Vector
这很好,直到我的输入数组没有实际以零开始/结束:
input = [ 1 2 0 3 4 0 0 0 0 ]
如果这是我的输入数组,那么上述问题的答案将切断我需要的值。
是否有一种简洁的方法(即不长“if”语句)移除前导/尾随零,而不能保证它们会存在?
编辑以求澄清:
我知道我可以使用find()
函数获得一个非零索引数组,然后执行如下操作:
indexes = find(input)
trimmed_input = input( indexes(1):indexes(end) )
但是出现了一个问题,因为我不能保证输入数组会有尾随/前导零,并且可能(很可能)在非零值之间有零。所以我的输入数组可以是:
input1 = [ 0 0 0 nonzero 0 nonzero 0 0 0 ] => [ nonzero 0 nonzero ]
input2 = [ nonzero 0 nonzero 0 0 0 ] => [ nonzero 0 nonzero ]
input3 = [ 0 0 0 nonzero 0 nonzero ] => [ nonzero 0 nonzero ]
input4 = [ 0 0 0 nonzero nonzero 0 0 0 ] => [ nonzero nonzero ]
input5 = [ 0 0 0 nonzero nonzero ] => [ nonzero nonzero ]
input6 = [ nonzero nonzero 0 0 0 ] => [ nonzero nonzero ]
使用上面的方法,无论是在input2
还是input3
上,都会修剪我想要保留的值。
发布于 2016-10-14 19:59:37
我现在可以想出一种简单的方法,但我认为这应该是可行的:
if input(1)==0
start = min(find(input~=0))
else
start = 1;
end
if input(end)==0
endnew = max(find(input~=0))
else
endnew = length(input);
end
trimmed_input = input(start:endnew);
编辑
哈,找到了一条班轮:)
trimmed_input = input(find(input~=0,1,'first'):find(input~=0,1,'last'));
不知道这到底是快还是不那么复杂。
另一种选择(理解@jrbedard的含义):
trimmed_input = input(min(find(input~=0)):max(find(input~=0)));
发布于 2016-10-14 19:11:03
https://stackoverflow.com/questions/40054494
复制相似问题