本文介绍了查找水平或垂直放置在矩阵中的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在大矩阵A中找到向量B.
B可以位于A的多行和一列中,也可以位于A的多列和一行中.

I'm trying to find a vector B in a big matrix A.
B can be in multiple rows and one column of A, or multiple columns and one row of A.

例如:

A = [56  55  53  52  53;
     49  45  44  45  47;
     33  30  31  34  35;
     34  34  27  24  26;
     44  48  45  35  24;
     56  57  57  53  39;
     62  62  62  60  55;
     62  61  61  54  47;
     49  47  42  40  32;
     47  42  44  45  40];

B = [34 27 24];

我需要一个返回行索引和col索引的函数,例如:
find(A,B)→第4行,第2至第4列(对于给定的示例).

I need a function that returns the row and col indices i.e. something like:
find(A, B) → 4th row, 2nd to 4th col (for the given example).

该怎么做?

推荐答案

rahnema1和m7913d之间的基准

水平和垂直匹配

在给定示例( Small A )和100^2大( Large A )的示例中,使用timeit对rahnema1和m7913d的解决方案进行基准测试,得出以下结果:

Benchmarking the solution of rahnema1 and m7913d using timeit for the given example (Small A) and one that is 100^2 larger (Large A), gives the following results:

Method   | Small A    | Large A
--------------------------------
rahnema1 | 4.0416e-05 | 0.0187
m7913d   | 2.5242e-05 | 0.0129

请注意,m7913d的解决方案速度提高了约50%.

Note that m7913d's solution is ~50% faster.

仅水平(或垂直)匹配

如果您仅对水平匹配感兴趣,则会获得以下结果:

If you are only interested in horizontal matches, the following results are obtained:

Method   | Small A    | Large A
--------------------------------
rahnema1 | 9.6752e-06 | 0.0115
m7913d   | 5.8634e-06 | 0.0056

在这种情况下,m7913d的解决方案更为优越,速度提高了约100%.

In this case, m7913d's solution is even more favorable, being up to ~100% faster.

完整的基准代码

A=[56  55  53  52  53;
  49  45  44  45  47;
  33  30  31  34  35;
  34  34  27  24  26;
  44  48  45  35  24;
  56  57  57  53  39;
  62  62  62  60  55;
  62  61  61  54  47;
  49  47  42  40  32;
  47  42  44  45  40];
B=[34 27 24];
A_large = repmat(A, 100, 100);

t_m7913d = timeit(@() m7913d(A, B))
t_rahnema = timeit(@() rahnema1(A, B))

t_large_m7913d = timeit(@() m7913d(A_large, B))
t_large_rahnema = timeit(@() rahnema1(A_large, B))

 function [row_h, col_h, row_v, col_v] = m7913d(A, B)
    Ah = true(size(A) - [0 length(B)-1]);
    Av = true(size(A) - [length(B)-1 0]);
    for i=1:length(B)
        Ah= Ah & A(:, i:end-3+i) == B(i);
        Av= Av & A(i:end-3+i, :) == B(i);
    end
    [row_h, col_h] = find(Ah);
    [row_v, col_v] = find(Av);
end

function [row_h, col_h, row_v, col_v] = rahnema1(A, B) 
    n = numel(B);
    C = A == reshape(B,1,1,n);
    mask_h = permute(eye(n),[3 2 1]);
    mask_v = permute(eye(n),[1 3 2]);
    [row_h, col_h]=find(convn(C,mask_h,'valid')==n);
    [row_v, col_v]=find(convn(C,mask_v,'valid')==n);
end

这篇关于查找水平或垂直放置在矩阵中的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 06:38