MATLAB: Is precision the reason the code doesn’t work

data processingdoublefor loopif statementmatrixmatrix manipulationprecision

I have a matrix (as attached) I try to find rows that has a specific number in the 2nd column as N. It works when try N=1 or N=0 and extract the the new data from the original DATA. But when I pick a number from column 2 other than 1 or 0 For example the number in DATA(3044,2) which is (0.123945562585054) the code doesNOT work. I'm wondering if it is the precision or what ? Any help is highly appreciated:
data=[];
N=1;
for j=1:length(DATA);
if DATA(j,2)==N;
data =[data;DATA(j,:)]
else
data=[data];
end
end

Best Answer

Yes, precision is the problem. You have to take special steps to be able to see the full precision of a number in order to be able to type it in with enough precision that you can do an exact comparison using "==" like you do.
I recommend that you use https://www.mathworks.com/matlabcentral/fileexchange/22239-num2strexact--exact-version-of-num2str- to look at what the numbers really stored are.
You should consider whether you really want to do exact bit-for-bit comparisons. Any two ways of computing values that are algebraically equivalent can have different round-off, so you should only ever use == to compare values that have been extracted from the same array. Otherwise you should compare with a tolerance.