1

In MATLAB R2016a, suppose that I define the array arr = -0.2:0.1:0.2. I may then find the location of the value el = 0.1 with the command idx = find(arr==el). This correctly yields idx = 4.

But now suppose that I define a larger array such as arr = -0.3:0.1:0.3. If I again try to find the location of the value el = 0.1 with the command idx = find(arr==el), I obtain an empty matrix. For some reason, MATLAB does not consider the 0.1-like element in arr to be equal to el = 0.1.

Why is this and how can I generate an array for which element-finding operations like the above work reliably?

4
  • 2
    “how can I generate an array for which element-finding operations like the above work reliably?” You can’t. Because 0.1 cannot be written exactly in binary. All you can do is improve your element-finding comparison (using a tolerance like in the linked answer) or change your problem so you only store integers in your array. Commented Jan 17, 2024 at 3:53
  • The answers of this question (stackoverflow.com/questions/23824577/…) basically answer my question above. Note especially the example, 0.1 + 0.1 + 0.1 == 0.3, which evaluates to False in MATLAB. The comparison of 1.2 - 0.2 - 1 == 0 and 1.2 - 1 - 0.2 == 0 is also interesting. Commented Jan 17, 2024 at 4:03
  • 2
    It's a shame this question is closed, because although all the relevant information is indeed in the linked answer, for the specific case here you can use MATLAB's ismembertol to solve your problem, like this: find(ismembertol(-0.3:.1:.3, 0.1)) Commented Jan 17, 2024 at 7:10
  • 1
    @Edric I've added OP's link as an additional duplicate since it relates specifically to options for comparisons, you could add using ismembertol as an answer to the duplicate since it's not currently listed. Commented Jan 17, 2024 at 8:12

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.