【问题标题】:Extracting positions of elements from two Matlab vectors satisfying some criteria从满足某些条件的两个 Matlab 向量中提取元素的位置
【发布时间】:2021-11-27 13:30:03
【问题描述】:

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

  • aA(a)A 中的位置。

  • bB(b)B 中的位置。

  • A(a)-B(b)C 的一个元素。

  • cA(a)-B(b)C 中的位置。

  • A(a)B(b)Inf-Inf 不同。

例如,

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

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

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

【问题讨论】:

  • 如果AB 变大,这可能在计算上变得非常昂贵,对这些值可能是什么或它们有多大有任何限制吗?否则很快就会有很多可能的 AB 元素配对进行测试

标签: arrays matlab


【解决方案1】:

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

  1. 找出差异
  2. 检查C中的差异
  3. 删除您不关心的元素

像这样:

% 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 个配对。这还不算太糟糕,但读者应该小心,对于更大的输入,配对可能会快速增长。

【讨论】:

  • 谢谢。我认为这也可以(从我之前的问题中获得灵感)[a, b] = ndgrid(A(~isinf(A)), B(~isinf(B)));[indAB, indC] = ismember(a-b, C);[posA, posB]=find(indAB);posC=nonzeros(indC);D = [posA posB posC];
  • 这看起来几乎是相同的逻辑,但是您要预先过滤掉 inf 值,在线执行 delta,并使用 find 来获得非ismember 的零索引输出。所以是的,不用自己运行它看起来不错
猜你喜欢
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-17
  • 1970-01-01
相关资源
最近更新 更多