Azzera filtri
Azzera filtri

Using ismembertol for multiple coincidences

4 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Bruno Luong
Bruno Luong il 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 Commenti
Jose Luis Villaescusa Nadal
Modificato: Jose Luis Villaescusa Nadal il 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 il 2 Nov 2022
Modificato: Bruno Luong il 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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Resizing and Reshaping Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by