Using ismembertol for multiple coincidences

4 次查看(过去 30 天)
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?

采纳的回答

Bruno Luong
Bruno Luong 2022-11-2
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 个评论
Jose Luis Villaescusa Nadal
编辑:Jose Luis Villaescusa Nadal 2022-11-2
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 2022-11-2
编辑:Bruno Luong 2022-11-2
You could use discretize with edges that are sort(A)-tol and sort(A)+tol instead of find. Details need to be worked out.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by