problem with if condition

조회 수: 3 (최근 30일)
milan pepa
milan pepa 2012년 3월 9일
hi, i have this problem with matlab. This is my m-file, but it doesnt work.
clear all
t=0:0.1:1;
k=length(t);
a=0;
for i=1:k
if a==0.8
disp('hi')
end
a=a+0.1
end
If i use this one
t=0:1:10;
k=length(t);
a=0;
for i=1:k
if a==8
disp('hi')
end
a=a+1
end
this one works well. The difference between first and second case is only that some variables are increased 10times. Please help. thank you

채택된 답변

Aldin
Aldin 2012년 3월 9일
Solution:
Here, try this algorithm:
clear all
t=0:0.1:1;
k=length(t);
a=0;
for i=1:k
b = num2str(a);
if strcmp(b,'0.8');
disp('hi')
end
a=a+0.1;
end
  댓글 수: 5
Walter Roberson
Walter Roberson 2012년 3월 9일
Using the string solution is not recommended. Instead use a tolerance on the comparison.
milan pepa
milan pepa 2012년 3월 9일
thank you Walter, it works great

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

추가 답변 (1개)

G A
G A 2012년 3월 9일
  댓글 수: 2
Walter Roberson
Walter Roberson 2012년 3월 9일
http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F
milan pepa
milan pepa 2012년 3월 9일
thank you

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

카테고리

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