If statement not executing

3 views (last 30 days)
GEON G BASTIAN
GEON G BASTIAN on 19 Feb 2020
Answered: David Hill on 19 Feb 2020
here, In my code, the statement to be executed after checking if abs(r1)==abs(v(i)) is not being executed. Why is that so? It is showing that Bm2 is an unrecognised variable, but clearly Bm2 will have a value if the if statement is executed.
r1 = round(r,1);
for i=1:length(v)
y2(i) = abs(p1* abs(v(i)*100)^4 + p2* abs(v(i)*100)^3 + p3*abs(v(i)*100)^2 + p4*abs(v(i)*100) + p5)/fd1;
B(i) = y2(i) * fd1;
end
for i=1:length(v)
if abs(r1) == abs((v(i)))
Bm2 = B(i) *10 ^-6;
else
end
end
for i=1:numel(u)
if u(i)==0
Bx(i)= Bm2;
else
y3(i) = abs((p11* abs(u(i))^3 + p12*abs(u(i))^2 + p13*abs(u(i)) + p14)/fd2) ;
Bx(i) = y3(i) * Bm2;
end
end
figure(2);
plot(u,Bx);

Accepted Answer

Fangjun Jiang
Fangjun Jiang on 19 Feb 2020
Edited: Fangjun Jiang on 19 Feb 2020
Most likely a "floating point data equal comparison" issue. see (1/3)==(1-2/3). They are not equal if you run it in MATLAB.
  3 Comments
Fangjun Jiang
Fangjun Jiang on 19 Feb 2020
The if statement is being executed but your code is not robust. Change to
if (abs(r1)-abs(v(i)))<=eps
Steven Lord
Steven Lord on 19 Feb 2020
It could be a floating-point issue, or it could be that r is a non-scalar and not all elements of r are equal to any of the v(i)'s.
If it's a floating-point issue, comparing with a tolerance is the usual approach. Using ismembertol instead of the loop and the equality testing is another option.
x = 0:0.1:1;
y = 0.3;
y == x(4) % false
abs(y-x(4)) < eps % true
ismembertol(y, x, eps) % true
If a vector issue, calling any is a potential solution.
if x == 0.5
disp('Yes')
else
disp('No')
end
if any(x == 0.5)
disp('Yes')
else
disp('No')
end

Sign in to comment.

More Answers (1)

David Hill
David Hill on 19 Feb 2020
You are overriding Bm2 unless there is only one case where abs(v)==abs(r1). You should be able to execute without loops. If you are having floating point issues, just add a tolerance.
r1 = round(r,1);
y2 = abs([p1,p2,p3,p4,p5]*abs((repmat(v,5,1)*100).^((4:-1:0)')))/fd1;
B = y2 * fd1;
Bm2 = B(abs(v)==abs(r1)) *10 ^-6;%is there only one case where v==r1? otherwise Bm2 will not be scalar
Bx(u==0)= Bm2;%Bm2 assumed to be scalar. Is Bx preallocated (Bx=zeros(1,length(u)))?
y3 = abs([p11,p12,p13,p14]*abs(repmat(u(u~=0),4,1).^((3:-1:0)')))/fd2);
Bx(u~=0) = y3 * Bm2;%Bm2 assume to be scalar
figure(2);
plot(u,Bx);

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!