MATLAB: using the find function to get indices of a certain value in an array

前端 未结 3 2042
面向向阳花
面向向阳花 2021-01-16 21:28

I have made an array of doubles and when I want to use the find command to search for the indices of specific values in the array, this yields an empty matrix which is not w

3条回答
  •  囚心锁ツ
    2021-01-16 22:12

    The problem is indeed with the precision. The array that you see displayed is not the actual array, as the actual array has more digits for each of the numbers. Changing the format just changes the way in which the array is displayed, so it doesn't solve the problem.

    You have two options, either modify the array or modify what you are looking for. It is probably better to modify what you are looking for, since then you are not changing the actual values.

    So instead of looking for equality, you can look for proximity (so the difference between the number you are searching for and the number in the array is at most some small epsilon):

    peaks = find( abs(y1-0.8236) < epsilon )
    

    In general, when you are dealing with floats, always try to avoid exact comparisons and use some error thresholds, since the representation of these numbers is limited so they are often stored with small inaccuracies.

提交回复
热议问题