Using ismembertol for multiple coincidences

4 vues (au cours des 30 derniers jours)
Jose Luis Villaescusa Nadal
Modifié(e) : Bruno Luong le 2 Nov 2022
I have two vectors, and I'm trying to find ALL coincidences of one on the other within a certain tolerance.
For example:
A = [5 3 4 2]; B = [2 4 4 4 6 8];
I want to obtain a cell array containing on each cell the numbers of all the coincidences with a tolerance of 1 (or more) units. (A = B +- 1)
I have a solution with zero units (A = B), which would look something like this:
tol = 0;
[tf, ia] = ismembertol(B,A,tol,'DataScale',1); % For tol = 0, this is equivalent to using ismember
idx = 1:numel(B);
ib = accumarray(nonzeros(ia), idx(tf), [], @(x){x}) % This gives the cell array
The output is:
ib =
[]
[]
[2 3 4]
[1]
Which is as desired.
If I change the tolerance to 1, the code doesn't work as intended. It outputs instead:
tol = 1
[tf, ia] = ismembertol(B,A,tol,'DataScale',1); % For tolerance = 1, this is equivalent to using ismember
idx = 1:numel(B);
ib = accumarray(nonzeros(ia), idx(tf), [], @(x){x}) % This gives the cell array
ib =
[5]
[2 3 4]
[]
[1]
When I would expect to obtain:
ib =
[2 3 4 5]
[1 2 3 4]
[2 3 4]
[1]
What am I doing wrong? Is there an alternative solution?

Réponse acceptée

Bruno Luong
Bruno Luong le 2 Nov 2022
Using ismembertol is inappropriate
A = [5 3 4 2]; B = [2 4 4 4 6 8];
tol = 1;
[ib,ia]=find(B'<=A+tol & B'>=A-tol);
c = accumarray(ia,ib,[numel(A) 1],@(x){x'})
c = 4×1 cell array
{[2 3 4 5]} {[1 2 3 4]} {[ 2 3 4]} {[ 1]}
c{:}
ans = 1×4
2 3 4 5
ans = 1×4
1 2 3 4
ans = 1×3
2 3 4
ans = 1
  3 commentaires
Jose Luis Villaescusa Nadal
Modifié(e) : Jose Luis Villaescusa Nadal le 2 Nov 2022
When A and B are long vectors, matlab quickly runs out of memory, since the find creates an array of size [numel(A), numel(B)]. Ismembertol, seems to be able to deal with this.
Do you think there is a way to overcome this with your solution?
Bruno Luong
Bruno Luong le 2 Nov 2022
Modifié(e) : Bruno Luong le 2 Nov 2022
You could use discretize with edges that are sort(A)-tol and sort(A)+tol instead of find. Details need to be worked out.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by