How to find the position(index) of a floating point number in matrix?
조회 수: 36 (최근 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에서 Logical에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!