当前位置: 动力学知识库 > 问答 > 编程问答 >

matlab - Find the first index such that all successive elements are zero

问题描述:

I have a vector in matlab

a = [1 8 0 7 0 5 9 0 0 0 0 0 0 0 0]

Here I am interested to FIND the first index (beyond which the value are completely zero) where the zeros occur continuously. In this example I expect the answer to be 8.

网友答案:
last_idx = max(find(a~=0)) + 1

however, if your last entry is not a zero you've to be careful...

网友答案:

find pretty much does this for you:

find(a, 1, 'last') + 1

since find just returns a list of the positions of non-zero characters, all you have to do is ask find to only give you the last such element and then the next element (hence the +1)

网友答案:

One approach that works even if your last entry is non-zero or your first entry is zero or all your entries are zero, covers just about everything.

find(diff([1 a]==0)==1,1,'last')

Note that this finds the location of the last group of zeros.

分享给朋友:
您可能感兴趣的文章:
随机阅读: