problems with function "find". matlab doesn't match two numbere which are built equal
10 views (last 30 days)
Show older comments
M cannot be found because Matlab says they are different, but i built them in order to be equal. length(data)=7155
clear all;clc;close all;
data0 = load('data0000.txt');
data1 = load('data0001.txt');
data2 = load('data0002.txt');
Rg=17.5;
fs = 100; % Hz
dt = 1/fs;
data= [data0; data1; data2];
time= 0:dt:(length(data)-1)*dt;
N=find(time==12.01);
M=find(time==46.5);
data=data(N:M,:);
time=time(N:M);
1 Comment
Accepted Answer
dpb
on 6 Oct 2018
dt = 1/fs;
data= [data0; data1; data2];
time= 0:dt:(length(data)-1)*dt;
is the root of the problem; can be demonstrated without the other data files...
>> time= 0:dt:(7155-1)*dt; % build the time vector based on length and dt
>> find(time==46.5) % and look for exact match...
ans =
1×0 empty double row vector
>>
which fails. Huh!???!!! Whassup w/ that--
>> find(time>46.5,1) % ok where is value close to it?
ans =
4651
>> time(4650:4652) % see what look like, to four decimal points matches
ans =
46.4900 46.5000 46.5100
>> time(4651)==46.5 % is it really so or did something go wrong internally
ans =
logical
0
>> time(4651)-46.5 % what's the difference between what "looks like" match and target?
ans =
7.1054e-15
>>
It is close, but not exact.
This is floating point roundoff wherein the multiple application of the FP approximation to 1/100 is accrued in the computations and sometimes the calculated number is not quite the same as a value entered as text or computed by another technique not subject to the same rounding.
>> time=linspace(0,7154/100,7155);
>> t1= 0:dt:(7155-1)*dt;
>> all(t1==time)
ans =
logical
0
>> sum(t1==time)
ans =
3941
>> max(abs(t1-time))
ans =
1.4211e-14
>> find(time==46.5) % with |linspace|, don't see same rounding error
ans =
4651
>>
However, still is much more robust to use ismembertol when searching/matching for floating point values unless can explicitly control rounding.
More Answers (1)
jonas
on 6 Oct 2018
Edited: jonas
on 6 Oct 2018
It is better to compare floats using a tolerance
tol=0.01;
M = find(abs(time-46.5)<tol);
I was however able to find the first number, N, using your code.
N =
1202
the second number, M, is probably in another textfile because there is no value near 46.5 in the one you attached
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!