【问题标题】:Cut off leading and trailing zeros from array, only if they exist从数组中截断前导零和尾随零,仅当它们存在时
【发布时间】: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 ]

使用上述方法,input2input3 将修剪我想要保留的值。

【问题讨论】:

  • 不,你的方法有效。你有没有尝试过?举一个失败的例子。
  • 嗯,我认为你是对的......我知道我认为这行不通是有原因的,也许我只是想得太用力了。编辑:我知道发生了什么,我在想我正在切片,但不包括数组为 0 的索引

标签: arrays matlab


【解决方案1】:

我现在可以想到一种巧妙的方法来做单行,但我认为这应该可行:

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);
  • 如果它以 0 开头,则需要找到第一个非零元素。
  • 如果它以 0 结尾,则需要找到最后一个非零元素。

编辑

哈,找到了一个班轮:)

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)));

【讨论】:

  • 是的,这或多或少是我现在所拥有的,我想它不会使功能减慢太多,它只是做一个相对简单的事情的大量代码,而且不是很可读。
  • 是的,我对它不太满意,遗憾的是 matlab 没有三元运算符。我想你可以把它们变成函数并隐藏讨厌的代码。
  • 更新为单线,我对自己很满意。
  • 很好,是的,我现在明白@jrbedard 的意思了,谢谢,这正是我想要的。非常简洁,但可能不如 if 语句可读性哈哈
【解决方案2】:

使用find 函数。

最后一个非零元素的索引由下式给出:

index = max(find(input~=0))

截断后的数组是:

trunc = input(1,index)

【讨论】:

  • 我认为这不会起作用,因为它只会找到最后一个非零元素。
  • 在使用find 查找最后N 个非零元素时,可以使用'last' 标志。在你的情况下,N 是 1...所以index = find(input ~= 0, 1, 'last');。顺便说一句,mpaskov 在他的陈述中是正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 2011-02-12
  • 2014-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多