How to find the position(index) of a floating point number in matrix?
35 次查看(过去 30 天)
显示 更早的评论
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
采纳的回答
Wayne King
2013-4-30
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 个评论
更多回答(1 个)
Jan
2013-4-30
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
...
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!