array indexing returns empty row vector while attempting to locate index corresponding to only certain array values
7 ビュー (過去 30 日間)
古いコメントを表示
An array (h) is defined:
h = 0.1:0.05:0.5;
while a separate array (index) is used to store corresponding indices to members of h:
index = 1:length(h);
While attempting to use array indexing to get index (of index) corresponding to h = 0.3, the return is a 1X0 empty double row vector. This similarly occurs when h = 0.15, 0.175, and 0.325 (within the domain of h).
index(h==0.3)
However, the correct index is returned for all other values of h. For example:
index(h==0.2)
Is there a reason why MATLAB would return an empty double row vector for the particular values as shown above?
The same problem exists for me using two independent machines (both Windows 64, one R2019b and other R2020b), and similar results occurred using the "RUN" feature of this thread while I was writing the description. Any help is greatly appreciated.
0 件のコメント
採用された回答
Dave B
2021 年 9 月 14 日
This is an issue of floating point arithmetic, another way to state the problem is:
(.1+.2)==.3
What? How can those not be equal? Actually they're really close:
(.1+.2) - .3
There are lots of threads about this on MATLAB Answers, this one is a good starter that links to more:
A (I know unsatisfying) answer may be to replace your == with a tolerance check:
h = 0.1:0.05:0.5;
index = 1:length(h);
tol = 1e-10;
index(abs(h-0.3) < tol)
2 件のコメント
Dave B
2021 年 9 月 16 日
No worries Aaron, one of the reasons this one comes up so much is that it's not intuitive (if you don't spend your days thinking about this kind of thing) and it's not totally obvious what to search for when you run into it!
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!