problem with if condition

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 日

0 投票

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 件のコメント

milan pepa
milan pepa 2012 年 3 月 9 日
thank you
Dont you know the reason why it works wrong in second case?
Aldin
Aldin 2012 年 3 月 9 日
I don't know. Maybe cause 0.8 is not equal to 0.8000 by using for loop.
Are you from Yugoslavia?:) See Walter Roberson link:
http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F
Aldin
Aldin 2012 年 3 月 9 日
Accept Answer if i was helpful.
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 日

0 投票

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

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by