从满足某些条件的两个 Matlab 向量中提取元素的位置

Extracting positions of elements from two Matlab vectors satisfying some criteria

考虑 Matlab 中的三个行向量,ABC,每个向量的大小为 1xJ。我想构建一个大小为 Kx3 的矩阵 D 列出每个三元组 (a,b,c) 这样:

例如,

A=[-3 3 0 Inf -Inf];
B=[-2 2 0 Inf -Inf];
C=[Inf -Inf -1 1 0];
D=[1 1 3;   %-3-(-2)=-1
   2 2 4;   % 3-2=1
   3 3 5];  % 0-0=0

我希望这段代码高效,因为在我的真实示例中我必须重复多次。

这个问题与我之前的问题有关,但现在我正在寻找元素的位置。

您可以使用 combvec(或 any number of alternatives)获取索引 ab 的所有配对,对应数组 AB。那么这只是一个遵循您的标准的情况

  1. 找不同
  2. 检查 C
  3. 中有哪些差异
  4. 删除您不关心的元素

像这样:

% Generate all index pairings
D = combvec( 1:numel(A), 1:numel(B) ).';
% Calculate deltas
delta = A(D(:,1)) - B(D(:,2));
delta = delta(:); % make it a column
% Get delta index in C (0 if not present)
[~,D(:,3)] = ismember(delta,C);
% If A or B are inf then the delta is Inf or NaN, remove these
idxRemove = isinf(delta) | isnan(delta) | D(:,3) == 0;
D(idxRemove,:) = [];

对于您的示例,这会产生问题的预期结果。

你说 AB 最多有 7 个元素长,所以你最多有 49 个配对要检查。这还不错,但读者应该注意,对于较大的输入,配对会快速增长。