필터 지우기
필터 지우기

Isempty in while loop not working

조회 수: 3 (최근 30일)
Diogo Nascimento
Diogo Nascimento 2017년 12월 15일
댓글: Diogo Nascimento 2017년 12월 15일
Hello! this might be a rookies mistake but I really cant understand whats happening... I have the code below, there is a large vector and I need to find where's a value in it. if the value doesnt exist I want to keep lowering it until I find one that does.
So in this case 0.4 doesn't exist neither 0.3 nor 0.2 but 0.1 does. the problem is that matlab runs for ever with my while loop and doesnt return k=1....
alpha=[0.1 0.5 0.9 1.3 1.9];
theta=0.4;
k = find(alpha==theta);
angle=theta;
while isempty(k)
angle=angle-0.1;
k = find(alpha==angle);
fprintf('The solution did not converge for %.2f so the angle %.2f is used. Extend the number of iterations to obtain solution \n',theta,angle);
end
thanks in advance!

채택된 답변

Stephen23
Stephen23 2017년 12월 15일
편집: Stephen23 2017년 12월 15일
"this might be a rookies mistake"
It is. The mistake occurs here:
alpha==angle
Small differences in the floating-point values mean that those values are actually different. Floating-point numbers have been explained a thousand times on this forum:
etc, etc, etc
Always use a tolerance when comparing floating point values.
  댓글 수: 1
Diogo Nascimento
Diogo Nascimento 2017년 12월 15일
amen to that! I was looking to the wrong part of the problem then :S
thanks!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by