简体   繁体   English

如何在数组中找到最后一个非零的元素的索引

[英]How to find the index of last element which is non-zero in array

I have a vector d that its size 1x1000 . 我有一个大小为1x1000的向量d It stores a random values from 0 to 1 . 它存储从01的随机值。 For example 例如

d=[0.0076 0.4629 0.1554...0 0 0 0 ...0.0442 0 0 0 10^-7 10^-7 10^-7] 

Now, I want to get the index of element at the last of vector (has maximize index) subject to non-zero or bigger than 10^-7 ). 现在,我想得到vector的最后一个元素的索引(具有最大化索引),取决于non-zero或大于10^-7 )。 For my example, the element that has value is 0.0442 and index= ?. 对于我的示例,具有值的元素是0.0442并且index= ?. How to implement it by MATLAB? 如何通过MATLAB实现它? Thank all 谢谢大家

To find the last element that satisfies a condition, you can use the syntax find(tf, 1, 'last') . 要查找满足条件的最后一个元素,可以使用语法find(tf, 1, 'last')

In your case, you want to find the last value that is more than a certain tolerance away from zero, ie 在您的情况下,您希望找到超过零的某个容差的最后一个值,即

tol = 2e-7;
idx = find( abs(d)>tol, 1, 'last');

Note: I've used abs(d) so that the solution is robust to negative values in the input, and I set the tolerance to 2e-7 to increase the likelihood that the threshold is in between the most likely good values and the most likely bad values (setting it to 1e-6 may be even safer). 注意:我使用了abs(d)因此解决方案对输入中的负值很稳健,并且我将容差设置为2e-7以增加阈值介于最可能的良好值和最大值之间的可能性可能是坏的值(将其设置为1e-6可能更安全)。

 ind = find(d ~= 0);
 ind(end) = % last nonzero index
 d(ind(end)) = % last nonzero element

You can add threshold: ind = find(d > 1e-7) 您可以添加阈值: ind = find(d > 1e-7)

If you also have negative data you may add threshold like ind = find(d > 1e-7 | d < -1e-7) 如果您还有负数据,您可以添加阈值,例如ind = find(d > 1e-7 | d < -1e-7)

You can use a combination of max and cumsum - 你可以使用maxcumsum的组合 -

tol = 1e-7; %// tolerance value
[~,index] = max(cumsum(d>tol))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM