Aps18
Aps18

Reputation: 441

Matlab if loop not working

%function [flag] =verify(area)

[FileName,PathName,FilterIndex]= uigetfile('*.tif','Select the signature file');
display(PathName) 
m=[PathName,FileName];
area=nor_area(m);
%display(area)

%area=0.8707;
class(area)

flag=0;
extract=xlsread('D:\Project\Image_processing\important\best.xlsx', 'CW4:CW17');
c=numel(extract);
display(c)
l=extract(1);
class(l)
display(l)
for k = 1:c
%x=extract(k);
if (l==area && flag==0)
     % display(extract(k)); 
      flag=1;
      display(flag)
end 
end
display(flag)

The above is my code for verification, i am not able to compare "l==area", even if the values are same am not able to enter inside the loop. If i try passing the value assume l=0.9999 and the area that i obtain to be the same , if i sent l value explicitly it works..!! but if i try using some function and pass the same value it wont work. I have tried checking the type by using class, both returns double.

Can anyone please help me out with this and if this approach is not good, suggest any alternative that may be used.

Upvotes: 0

Views: 1119

Answers (2)

Chris
Chris

Reputation: 46316

It is not generally a good idea to compare floats like you are doing (with the == operator) since floats, unlike integer values are subject to round off. See here and here for a discussion on comparing floats in MATLAB.

Essentially you have to check that two floats are 'close enough' rather than exactly equal, which is what == checks for. MATLAB has a built in function eps for determining the floating point precision on your machine, so use that function when comparing floats. See its documentation for more information.

Upvotes: 3

Boris
Boris

Reputation: 7132

In most cases it is not wise to compare floating point numbers by a == b. Use abs(a-b)<epsilon where epsilonis some small tolerance like 1e-10 instead.

Upvotes: 2

Related Questions