Why does my if condition only work once?
    3 views (last 30 days)
  
       Show older comments
    
In the code here, while I expect the variable g2 to have a value of 1100 * 5, at some point I get a value of 1100 * 1 due to not making an error. 
Why does my if condition only work once, what am I missing?
clc;
clear all;
dt=0.01;
time_vec=0:dt:60;
Twin=11;
ors=0.4;
g2=[];
f2=[];
j=1;
l=1;
for z = 1:1:length(time_vec)
    time_vec_o(z)=dt*z+Twin*ors;
    f2(j)=1/2*(1-cos(2*pi*(dt*z+Twin*ors)/Twin));
    a(z)= time_vec_o(z);
    b(z)=mod(time_vec_o(z),Twin);
    if  a(z)>=Twin*ors+Twin && b(z)==Twin*ors
        g2(:,l)=f2;
        f2 = [];
        j = 1;
        l=l+1;
    else
        j = j + 1;
    end
end
1 Comment
  Stephen23
      
      
 on 26 Feb 2023
				On this line:
if  a(z)>=Twin*ors+Twin && b(z)==Twin*ors
you are assuming that you can test for exact equivalence of binary floating point values. That is rarely a good approach. The robust approach is to compare the absolute different against a tolerance:
abs(A-B)<tol
Read about the nature of working with binary floating point numbers:
This is highly recommended:
Answers (0)
See Also
Categories
				Find more on Loops and Conditional Statements 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!