从满足某些条件的两个 Matlab 向量中提取元素的位置
Extracting positions of elements from two Matlab vectors satisfying some criteria
考虑 Matlab 中的三个行向量,A
、B
、C
,每个向量的大小为 1xJ
。我想构建一个大小为 Kx3
的矩阵 D
列出每个三元组 (a,b,c)
这样:
a
是 A(a)
在 A
中的位置。
b
是 B(b)
在 B
中的位置。
A(a)-B(b)
是 C
.
的一个元素
c
是 A(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
我希望这段代码高效,因为在我的真实示例中我必须重复多次。
这个问题与我之前的问题有关,但现在我正在寻找元素的位置。
您可以使用 combvec
(或 any number of alternatives)获取索引 a
和 b
的所有配对,对应数组 A
和 B
。那么这只是一个遵循您的标准的情况
- 找不同
- 检查
C
中有哪些差异
- 删除您不关心的元素
像这样:
% 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,:) = [];
对于您的示例,这会产生问题的预期结果。
你说 A
和 B
最多有 7 个元素长,所以你最多有 49 个配对要检查。这还不错,但读者应该注意,对于较大的输入,配对会快速增长。
考虑 Matlab 中的三个行向量,A
、B
、C
,每个向量的大小为 1xJ
。我想构建一个大小为 Kx3
的矩阵 D
列出每个三元组 (a,b,c)
这样:
a
是A(a)
在A
中的位置。b
是B(b)
在B
中的位置。
的一个元素A(a)-B(b)
是C
.c
是A(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
我希望这段代码高效,因为在我的真实示例中我必须重复多次。
这个问题与我之前的问题
您可以使用 combvec
(或 any number of alternatives)获取索引 a
和 b
的所有配对,对应数组 A
和 B
。那么这只是一个遵循您的标准的情况
- 找不同
- 检查
C
中有哪些差异
- 删除您不关心的元素
像这样:
% 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,:) = [];
对于您的示例,这会产生问题的预期结果。
你说 A
和 B
最多有 7 个元素长,所以你最多有 49 个配对要检查。这还不错,但读者应该注意,对于较大的输入,配对会快速增长。