仅在存在零和零的情况下才从数组中切除零 [英] Cut off leading and trailing zeros from array, only if they exist

查看:92
本文介绍了仅在存在零和零的情况下才从数组中切除零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试截取可能包含或不包含它们的输入数组的前导零和/或尾随零.我已经看到了以下问题的答案:

I am trying to cut off the leading and/or trailing zeros of an input array that may or may not have them. I have seen the answers to questions like:

MATLAB-删除向量中的前导零和尾随零

在我的输入数组实际上不以零开始/结束之前,这一直很好:

And this works fine until my input array doesn't actually start/end with zeros:

input = [ 1 2 0 3 4 0 0 0 0 ]

如果这是我的输入数组,则上述问题的答案将切断我所需的值.

If this was my input array, the answer to the above question would cut off values that I need.

在无法保证前导零位/尾随零位时,是否有一种简洁的方法(即没有长的"if"语句)?

Is there a succinct way (i.e. no long 'if' statements) to remove leading/trailing zeros, when there is no guarantee that they will be there?

为澄清起见进行

我知道我可以使用find()函数获取非零索引数组,然后执行以下操作:

I know that I can use the find() function to get an array of nonzero indexes, and then do something like:

indexes = find(input)
trimmed_input = input( indexes(1):indexes(end) )

但是出现一个问题,因为我不能保证输入数组将具有尾随/前导零,并且可能(可能会)在非零值之间具有零.所以我的输入数组可能是以下之一:

But a problem arises, because I have no guarantee that the input array will have trailing/leading zeros, and may (probably will) have zeros in between nonzero values. So my input array could be one of:

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上将修剪我要保留的值.

And using the method above, on either input2 or input3 will trim values that I want to keep.

推荐答案

我现在可以想到一种简单的方法来完成它,但是我认为这应该可行:

I can think of neat way to do it one-liner at the moment, but i think this should work:

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结尾,则需要找到最后一个非零元素.
  • 编辑

    哈,找到了一根衬里:)

    Ha, found the one liner :)

    trimmed_input = input(find(input~=0,1,'first'):find(input~=0,1,'last'));
    

    不知道这实际上是快速的还是不太复杂.

    No idea of if this is actually fast or is less complex.

    另一种选择(理解@jrbedard的意思):

    Another alternative (understood what @jrbedard meant):

    trimmed_input = input(min(find(input~=0)):max(find(input~=0)));
    

    这篇关于仅在存在零和零的情况下才从数组中切除零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆