Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersect two arrays with tolerance

Tags:

arrays

matlab

I have 2 arrays of data, from which I want to extract common elements. Matlab's intersect does this job. But it returns elements that are exactly the same. What if I want to extract elements with some tolerance? Say for e.g

A = [1 2 3.0002 4.125 5.89]; 
B = [2 3.012 4.126]

I want to extract elements that are same up to 2 decimal places. So I want the answer to be [2 4.12] . Is there any built-in function to do this? Or How do I achieve this?

like image 713
Rhinocerotidae Avatar asked Apr 07 '26 00:04

Rhinocerotidae


2 Answers

I would just round the input:

C = intersect(round(A,2),round(B,2))

floor and ceil are also options, depending on what you really want to achieve.

like image 193
Robert Seifert Avatar answered Apr 08 '26 15:04

Robert Seifert


You can do it manually as follows. This picks the output values from A; if you want to pick from B just swap A and B in the code:

A = [1 2 3.0002 4.125 5.89]; 
B = [2 3.012 4.126];
tol = .01;
result = A(any(abs(bsxfun(@minus, A(:).', B(:))) < tol, 1));
like image 26
Luis Mendo Avatar answered Apr 08 '26 15:04

Luis Mendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!