查找两个向量之间的多个重合

hav*_*ife 5 arrays matlab slice

我有两个向量,并且我试图在不使用 for 循环的情况下在一定容差内找到一个向量与另一个向量的所有重合。\n容差我的意思是,例如,如果我有数字 3,容差为 2,我会想要将值保持在 3\xc2\xb12 范围内,即 (1,2,3,4,5)。

\n
A = [5 3 4 2]; B = [2 4 4 4 6 8];\n
Run Code Online (Sandbox Code Playgroud)\n

我想要获得一个元胞数组,其中每个元胞上包含所有重合的数量,容差为 1(或更多)单位。(A = B +- 1)\n我有一个单位为零的解 (A = B),如下所示:

\n
tol = 0;\n[tf, ia] = ismembertol(B,A,tol,'DataScale',1); % For tol = 0, this is equivalent to using ismember\nidx = 1:numel(B);\nib = accumarray(nonzeros(ia), idx(tf), [], @(x){x}) % This gives the cell array\n
Run Code Online (Sandbox Code Playgroud)\n

输出是:

\n
ib = \n[]\n[]\n[2 3 4]\n[1]\n
Run Code Online (Sandbox Code Playgroud)\n

这是所期望的。\n如果我将容差更改为 1,则代码将无法按预期工作。它输出:

\n
tol = 1\n[tf, ia] = ismembertol(B,A,tol,'DataScale',1); % For tolerance = 1, this is equivalent to using ismember\nidx = 1:numel(B);\nib = accumarray(nonzeros(ia), idx(tf), [], @(x){x}) % This gives the cell array\nib = \n[5]\n[2 3 4]\n[]\n[1]\n
Run Code Online (Sandbox Code Playgroud)\n

当我期望获得:

\n
ib = \n[2 3 4 5]\n[1 2 3 4]\n[2 3 4]\n[1]\n
Run Code Online (Sandbox Code Playgroud)\n

我究竟做错了什么?有替代解决方案吗?

\n

Bil*_*eey 3

Your problem is that, in the current state of your code, ismembertol only outputs 1 index per element of B found in A, so you lose information in the cases where an element can be found several times within tolerance.

根据文档 You can use the 'OutputAllIndices',true value pair argument syntax, to output what you want in ia with just a call to ismembertol:

A = [5 3 4 2]; B = [2 4 4 4 6 8];

tol = 0;
[tf, ia] = ismembertol(A,B,tol,'DataScale',1,'OutputAllIndices',true);
Run Code Online (Sandbox Code Playgroud)

celldisp(ia) % tol = 0

ia{1} =

 0

ia{2} =

 0

ia{3} =

 2
 3
 4

ia{4} =

 1
Run Code Online (Sandbox Code Playgroud)

celldisp(ia) % tol = 1

ia{1} =

 2
 3
 4
 5

ia{2} =

 1
 2
 3
 4

ia{3} =

 2
 3
 4

ia{4} =

 1
Run Code Online (Sandbox Code Playgroud)

  • 值得一提的是,这个答案中的值“ia”取代了OP中的“ib”变量。 (3认同)