Borrar filtros
Borrar filtros

How to find the position(index) of a floating point number in matrix?

35 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Wayne King
Wayne King el 30 de Abr. de 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

Más respuestas (1)

Jan
Jan el 30 de Abr. de 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 comentarios
Novice Geek
Novice Geek el 30 de Abr. de 2013
Yes, you are correct, the actual data is similar to 1498.199999999999999. I tried using format short g for simplicity. I tried using the limit, and the modified function works perfectly from the range 200 - 300 (including index for floating point) in the column matrix. But the function does not give the position (index) of floating point numbers after 300 ranging upto 1500.
Here is what the modified function looks like:
columnmzData = mzData;
length = size(columnmzData);
i=1;
for mzDataLoop = 1:6501
limit = 1e-5;
if abs(columnmzData(mzDataLoop) - mzValue) < limit
mzValueIndice = i
break;
else
i=i+1;
end
end
Novice Geek
Novice Geek el 30 de Abr. de 2013
The function works for all values after a little tweaking. Thank you :)

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by