Strange issue with if expression, failing to compare two variables properly

Hi I'm having this small snippet, i'm finding values of coordinates as Lx1 and Lx2. they are same but if condition is jumping out to else clause! i've no clue on why its happening am i missing something obvious!
%%
line1 = [2 5 0 ; 9 1 0 ];
line2 = [1 1 0 ; 13 13 0];
line1_vector = ( line1(2,:) - line1(1,:)) / sqrt ( sum((line1(1,:)-line1(2,:) ).^2));
line2_vector = (line2(2,:) - line2(1,:)) / sqrt ( sum((line2(2,:)-line2(1,:) ).^2));
matrix_A = [ line1_vector(1:2)' -1*line2_vector(1:2)'];
matrix_b = [line2(1,1:2)' - line1(1,1:2)'];
parameter_matrix = matrix_A\ matrix_b;
Lz1 = line1(1,3) + parameter_matrix(1)*line1_vector(3)
Ly1 = line1(1,2) + parameter_matrix(1)*line1_vector(2);
Lx1 = line1(1,1) + parameter_matrix(1)*line1_vector(1)
Lz2 = line2(1,3) + parameter_matrix(2)*line2_vector(3)
Ly2 = line2(1,2) + parameter_matrix(2)*line2_vector(2);
Lx2 = line2(1,1) + parameter_matrix(2)*line2_vector(1)
if (Lz1==Lz2)
if (Lx1==Lx2)
status =0
else
status =1
end
end

 Accepted Answer

I doubt they are the same. Even if they are meant to be the same, there are bound to be small floating point round-off errors making them different. Use a tolerance,
if abs(Lx1-Lx2)<somethingsmall

1 Comment

yes i did it before posting question but i guess my something small was too small, These issues are very dangerous and hard to trace bugs. with matlab i was supposed to take care of maths and not worry about numerical limits. but guess its not easy to get rid of numerical noise Thanks for quick answer..

Sign in to comment.

Asked:

on 2 Jun 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!