1

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
novicegeek
  • 773
  • 2
  • 9
  • 29

2 Answers2

4

For floating point numbers rather look for a tiny difference than perfect equality so in your code columnmzData(mzDataLoop) == mzValue becomes abs(columnmzData(mzDataLoop) - mzValue) < tol where tol is a very small and depends on the tolerance of your numbers.

Have a look at this question to understand better

However you shouldn't be using a loop at all! Try the find function:

mzValueIndice = find(columnmzData == mzValue) %for ints
mzValueIndice = find(abs(columnmzData - mzValue) < tol) %for floats
Community
  • 1
  • 1
Dan
  • 45,079
  • 17
  • 88
  • 157
3

Finding the exact float value is hard, maybe you can specify a tolerance?

if (abs(columnmzData(mzDataLoop) - mzValue) < tolerance)
norq
  • 1,404
  • 2
  • 18
  • 35