在Matlab中找到矩阵中的一对数字

时间:2017-03-19 11:13:20

标签: matlab

鉴于矩阵A = [6 4 1; 1 4 3; 3 4 2;7 6 8]和对b = [4 6; 4 1; 1 6]数组,我想找到bA行中给出的对,而不是for }循环。

例如,第一对是(4,6)或(6,4),它出现在A的第一行。

1 个答案:

答案 0 :(得分:1)

假设您要查找A的行,其中包含b中给出的确切对,这是您可以在没有循环的情况下执行此操作的方法:

% Create a matrix of pairs in A
pairs = cat(3, A(:, 1:end-1), A(:, 2:end));

% Reshape b to use bsxfun
b_ = reshape(b', [1 1 size(b')]);

% Get the matches for the pairs and for the flipped pairs
indices =  all( bsxfun(@eq, pairs, b_), 3) | all( bsxfun(@eq, pairs, flip(b_,3)), 3);

% Find the indices of the rows with a match
row_indices = find(squeeze(any(any(indices,4),2)));

有关如何在没有循环的情况下在Matlab中进行快速计算的更多信息,请参阅the reference on vectorization