【发布时间】:2016-10-15 03:03:44
【问题描述】:
我正在尝试截断输入数组的前导零和/或尾随零,这些零可能有也可能没有。我已经看到了以下问题的答案:
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 将修剪我想要保留的值。
【问题讨论】:
-
不,你的方法有效。你有没有尝试过?举一个失败的例子。
-
嗯,我认为你是对的......我知道我认为这行不通是有原因的,也许我只是想得太用力了。编辑:我知道发生了什么,我在想我正在切片,但不包括数组为 0 的索引