Vector comparison by value produces strange results
13 views (last 30 days)
Show older comments
Hello,
I have two vectors and I think they are the same, but MATLAB says all the elements are different.
>> whos x
Name Size Bytes Class Attributes
x 1138x1 9104 double
>> whos x2
Name Size Bytes Class Attributes
x2 1138x1 9104 double
>> x(1) == x2(1)
ans =
0
>> x(1)
ans =
0.6557
>> x2(1)
ans =
0.6557
Why is this? Thank you.
2 Comments
Stephen23
on 4 May 2018
Never use exact equivalence to test if decimal values are the same: always compare the difference against a tolerance:
abs(A-B)<tol
You need to learn about the practical limits of floating point numbers:
And some external links on this topic:
Accepted Answer
jonas
on 3 May 2018
try to type
format long
and compare again
2 Comments
Stephen23
on 4 May 2018
"Is there a way to compare only the first 4 digit for example?"
This topic has been discussed many times on this forum: you should compare absolute difference against a tolerance, as I showed in my comment to your original question. Note that using round is popular with beginners, but it introduces artifacts into your data that do not actually exist. Read this to know more:
More Answers (0)
See Also
Categories
Find more on Data Type Identification 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!