Problem with intersect function
6 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Star Strider
on 14 Jul 2020
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 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!