How to find the position(index) of a floating point number in matrix?
36 views (last 30 days)
Show older comments
I am writing a function wherein I need to read a 6501 X 1 matrix and then find the index of a specific number which is provided by the user as an input. I am able to find the position of integer values but not of floating point numbers which are present in the column. Can anyone please help? Thank you
Below is the part of the function which loops through the column matrix to find the index of a number
format short g
columnmzData = mzData; % mzData is the column matrix
length = size(columnmzData);
i=1;
for mzDataLoop = 1:6501
if (columnmzData(mzDataLoop) == mzValue)
mzValueIndice = i
break;
else
i=i+1;
end
end
Here is the part of the column matrix:
1498
1498.2
1498.4
1498.6
1498.8
1499
1499.2
1499.4
1499.6
1499.8
Accepted Answer
Wayne King
on 30 Apr 2013
You can use a tolerance to find the nearest floating point number. If you make the tolerance small enough, it should work.
x = randn(100,1);
x([10 20]) = 2.501;
Now say I want to find all elements in x that are within 10^(-3) of 2.5
num = 2;
idx = find(abs(x-2.5)<1e-3);
You should see that idx minimally contains 10 and 20
0 Comments
More Answers (1)
Jan
on 30 Apr 2013
Specifying "format short g" means, that only a small number of digits is shown in the command line. When you "see" the value 1498.2 there, it could be 1498.1999999999999998 in reality. Then searching for 1498.2 cannot work.
The standard solution for these "problems" is to define a certain limit:
limit = 1e-5;
if abs(columnmzData(mzDataLoop) - mzValue) < limit
...
2 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!