If statement not executing

조회 수: 5 (최근 30일)
GEON G BASTIAN
GEON G BASTIAN 2020년 2월 19일
답변: David Hill 2020년 2월 19일
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);

채택된 답변

Fangjun Jiang
Fangjun Jiang 2020년 2월 19일
편집: Fangjun Jiang 2020년 2월 19일
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
Fangjun Jiang
Fangjun Jiang 2020년 2월 19일
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 2020년 2월 19일
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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

David Hill
David Hill 2020년 2월 19일
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);

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by