-2

I'm working on counting numbers using if-else statement. I'm getting the result, but it's only executing the else part and not looking at the other part.

This is the code I'm working with

i = 0;
j = 0;

if sum( abs( f1(:) - f2(:))) == 0.0
   i = i + 1;
else
   j = j + 1;
end
if sum(abs(f2(:) - f3(:))) == 0.0
   i = i + 1;
else
   j = j + 1;
end
if sum(abs(f3(:) - f4(:))) == 0.0
   i = i + 1;
else 
   j = j + 1;   
end

msgtext = sprintf('Matching = %d',i);
h = msgbox(msgtext);

msgtxt = sprintf(' Not Matching = %d',j);
h = msgbox(msgtxt);

Any suggestions?

Thanks in advance!

varsha_holla
  • 852
  • 7
  • 23
  • 41
  • 5
    [`Your buddy`](http://stackoverflow.com/q/30244098/3293881) might help you. – Divakar May 15 '15 at 07:23
  • @Divakar I tried that too. But its not working. – varsha_holla May 15 '15 at 07:31
  • 2
    We answerers try to be clairvoyant, but its not working. – Divakar May 15 '15 at 08:09
  • 1
    What are you trying to achieve with `sum( abs( f1(:) - f2(:))) == 0.0`? Are you just checking if the vectors are the same? Rather use `isequal(f1,f2)` if that's the case, although depending on the nature of your `f` matrices you may still face the issue of floating point precision truncation in which case see my answer. This question is poorly stated btw, please read [ask] – Dan May 15 '15 at 08:27
  • Also I suggest you do not use the terrible variable names `i` and `j` but rather choose something that conveys their meaning like `count_match` and `count_not_match` – Dan May 15 '15 at 08:32

1 Answers1

3

Your question is extremely vague so I'm going to pretend you only asked about one of the ifs:

if sum( abs( f1(:) - f2(:))) == 0.0
   i = i + 1;
else
   j = j + 1;
end

I think there is a fair chance that you only ever fall into the else clause because you are trying to equate floating point numbers, and that is a bad idea due to precision errors. This depends on the nature of f1 and f2, are they doubles, how were the calculated etc which you have given no indication of in your question. If you want to understand why you can't equate floating point numbers (or expect there difference to equal 0) then you must read What every computer scientist needs to know about floating-point arithmetic

Rather try if sum( abs( f1(:) - f2(:))) < tol where tol (i.e. tolerance) is a really tiny number (e.g. eps, but just choose a number that is orders of magnitude less than your application could produce.).

Dan
  • 45,079
  • 17
  • 88
  • 157