Problem with intersect function

6 ビュー (過去 30 日間)
JC
JC 2020 年 7 月 14 日
コメント済み: Star Strider 2020 年 7 月 14 日
I am using the intersect function but it seems to be giving only a subset of the common values in the two vectors being compared. I'm not sure if this is because of the way I have set up the vectors or whether I'm using the function incorrectly.
This is a simpler version of the code but with the same results:
z = -1:0.01:1;
zstart = linspace(-1,0.8,10);
zend = linspace(-0.8,1,10);
zmid = round((zstart+zend)/2,1);
[~,izmid] = intersect(z,zmid);
It should give the 10 indices of z which equal the values of zmid but it is only producing 6 of these.

採用された回答

Star Strider
Star Strider 2020 年 7 月 14 日
The intersectt function does not allow tolerances, so floating-point approximation error is going to present problems.
Try this:
z = -1:0.01:1;
zstart = linspace(-1,0.8,10);
zend = linspace(-0.8,1,10);
zmid = round((zstart+zend)/2,1);
% [~,izmid] = intersect(z,zmid);
izmid2 = ismembertol(z,zmid,1E-2); % Use Appropriate Tolerance Value (Here: 1E-2)
idx = find(izmid2); % Indices Corresponding To Logoical Vector ‘izmid2’
z_common = z(idx); % Common Values (± Tolerance Value)
Note the difference in results.
See the documentation on Floatinig-Point Numbers for a discussion of the reason ismembertol works here.
.
  2 件のコメント
JC
JC 2020 年 7 月 14 日
Thank you, that's really helpful!
Star Strider
Star Strider 2020 年 7 月 14 日
As always, my pleasure!

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by