Problem with ismember with certain numbers in a loop

10 ビュー (過去 30 日間)
Libby M
Libby M 2019 年 9 月 3 日
コメント済み: Star Strider 2019 年 9 月 3 日
Here is the code I have writen, as far as I can see B should alternating 1 and 0 (B=1, 0, 1, 0, 1 etc) but at (as far as I can tell) random points it does not do that. I can't see what I have done wrong and I don't know if I have misunderstood something with "ismember".
I have noticed this with number=0.3250 for example, ismember(number, setcom)=0 but ismember(0.3250, setcom)=1. If however I pause the code type in compand line "number" I get 0.3250 and I get ismember(number, setcom)=0, but if in the comand line I also type "number =0.3250" and then ismember(number, setcom)=1.
I don't understand why it works for most numbers in the loop but not all. Any help would be very much appreciated.
set=[0.125:0.0125:0.5];
setcom=[0.125:0.025:1];
B=zeros(length(set), 1);
for i=1:length(set)
number=set(i);
compare=ismember(number,setcom);
B(i,1)=compare;
end
  2 件のコメント
KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 9 月 3 日
set=(0.125:0.0125:0.5);
setcom=(0.125:0.025:1);
B=zeros(length(set),1);
compare=ismember(set,setcom)
Is there loop necessity? Note on Floating points number as answered by @Star
Libby M
Libby M 2019 年 9 月 3 日
Thank you, the loop is necessary for the rest on the code which I didn't put on here but yes are right for what I put up it is not needed. Unfortunately using compare=ismember(set,setcom) still has the same issue as the loop.

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

採用された回答

Star Strider
Star Strider 2019 年 9 月 3 日
Use ismembertol instead. You are likely dealing with ‘floating-point approximation error’. See Floating-Point Numbers for a full discussion.
  2 件のコメント
Libby M
Libby M 2019 年 9 月 3 日
Thank you for pointing this out to me
Star Strider
Star Strider 2019 年 9 月 3 日
As always, my pleasure!
This is one of the many interesting aspects of digital computations.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by