Filter löschen
Filter löschen

How to find similar elements with small difference (+/- 5%)?

1 Ansicht (letzte 30 Tage)
Ivan Shorokhov
Ivan Shorokhov am 2 Jul. 2015
Bearbeitet: Ivan Shorokhov am 2 Jul. 2015
Given: I have 2 arrays. For example: A = [97.2 103.4 109.6]; B = [99.0 105.2 111.4];
Want: I want to find nearest common values with difference +/- 5%. Such as:
D =
A B
------- -------
97.2 99.0
103.4 105.2
109.6 111.4
Currently done:
A = [97.2; 103.4; 109.6];
B = [99.0; 105.2; 111.4];
[E,IA,IB] = intersect(round(A.*0.1),round(B.*0.1),'sorted');
D = [A(IA) B(IB)];
Here is the output:
D =
A B
------- -------
97.2000 99.0000
109.6000 105.2000
As you can see I lost 2 values, and last row is also messed up.
Needed: So I'm wondering, if there are any other functions or code I could use to find similar elements with small difference (+/- 5%).
[ACKNOWLEDGMENTS]
Thanks you: Thorsten,Jan Simon,
I will vote for all your answers.
[MATLAB version]
R2014a

Akzeptierte Antwort

Thorsten
Thorsten am 2 Jul. 2015
One way would be to do this in a straight-forward loop:
p = 0.05; % percentage of difference accepted
C = nan(1, numel(A));
for i = 1:numel(A)
[d ind] = min(abs(B - A(i)));
if d < abs(p*A(i)), C(i) = B(ind(1)); end
end
D = [A' C'];
  1 Kommentar
Ivan Shorokhov
Ivan Shorokhov am 2 Jul. 2015
Bearbeitet: Ivan Shorokhov am 2 Jul. 2015
@Thorsten
Thank you for the great solution, it seems to be working fine for this particular case. I will test it larger data-set and will let you know, whether it works or not.
And there is small mistake in the last line. It should be:
D = [A C'];

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Jan
Jan am 2 Jul. 2015
Bearbeitet: Jan am 2 Jul. 2015
What about the new function ismembertol ?
[EDITED] And for older Matlab versions: FEX:ismemberf

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by