while using "find" on a vector I get "Empty matrix: 1-by-0" on certain values

Hi, I'm trying to make a program that takes values from a potentiometer into an Arduino but I keepp having the same problem where certain values in a vector (y=0:0.1:5) like 3.6 gives me the "Empty matrix: 1-by-0" error, here is an example of this problem
clc
y=0:.1:5;
for i=y
i;
j=round(i,1);
hp=find(y==j)
end
I think that round part is part of the problem but I need it for my program, help!

 Accepted Answer

The round function is not part of the problem. The inexact results of floating point calculations are. See Why is 0.3 - 0.2 - 0.1 (or similar) not equal to zero? (link) for an explanation.
You need to include some sort of tolerance, and one way of doing that is:
hp = find(y >= j, 1, 'first')
or:
hp = find(y <= j, 1, 'last')
These will allow for ‘floating-point approximation error’, and return the linear index of the nearest element.

2 Comments

thank you, I was getting really desperate
As always, my pleasure.
Understanding floating-point approximation error can prevent much anxiety. This is the reason the ismembertol, uniquetol, and related functions were developed.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!