你怎么指望在一个数组的开头和结尾相邻零的个数? [英] How do you count the number of adjacent zeros at the beginning and end of an array?

查看:104
本文介绍了你怎么指望在一个数组的开头和结尾相邻零的个数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下数组研究

>> A=[1:10];
>> r=(A>=2&A<=8)
r =
     0     1     1     1     1     1     1     1     0     0

我怎么算零的数量上的阵列的每一面?

How do I count the number of zeroes on each side of an array?

推荐答案

我假设你要计算的领导和阵列中的尾随零数。我们可以用两个找到只寻找一个非零元素第一次出现要求做到这一点。 1减去第一个非零元素的索引将告诉你有多少零但是也有一些领导。当他们开始在1,他们应该开始为0,那么就没有必要减法为什么我们用1减去其原因是由于道路MATLAB指标阵列。如果你想的结尾零,查找在最后非零元素。从这个点到结束元素的量是多少零元素有。因此:

I'm assuming you want to count the number of leading and trailing zeroes in an array. We can do this with two find calls with only searching for the first occurrence of a non-zero element. The index of the first non-zero element subtracted by 1 will tell you how many zeroes there are that are leading. The reason why we subtract by 1 is due to the way MATLAB indexes arrays as they start at 1. Should they start at 0, then there's no need for the subtraction. If you want trailing zeroes, look for the last non-zero element. The amount of elements from this point to the end are how many zero elements there are. Therefore:

num_leading = find(r, 1, 'first') - 1;
num_trailing = numel(r) - find(r, 1, 'last');

通过你的榜样,我们得到如下:

With your example, we get the following:

num_leading =

     1

num_trailing =

     2


更多的例子,为您展现这个作品:


Some more examples for you to show that this works:

r = [1 1 1 1 1 0 1 0 0];
num_leading = find(r, 1, 'first') - 1
num_trailing = numel(r) - find(r, 1, 'last')

num_leading =

     0

num_trailing =

     2

例2

r = [1 1 1 0 0 1 1 1 0 1];
num_leading = find(r, 1, 'first') - 1
num_trailing = numel(r) - find(r, 1, 'last')

num_leading =

     0


num_trailing =

     0

例#3

r = [0 0 1 0 1 1 0 1 0 0];
num_leading = find(r, 1, 'first') - 1
num_trailing = numel(r) - find(r, 1, 'last')

num_leading =

     2


num_trailing =

     2


正如你所看到的,这可以适应您的阵列可以采取任何形状,只要它是一维和行向量。


As you can see, this can adapt to any shape your array can take, provided that it is 1D and a row vector.

这篇关于你怎么指望在一个数组的开头和结尾相邻零的个数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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