Matlab如何找出矩阵是否在另一个矩阵中 [英] Matlab how to find out if a matrix is in another martrix

查看:983
本文介绍了Matlab如何找出矩阵是否在另一个矩阵中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我用一个例子来描述我的问题.假设我们有矩阵A:

Let me describe my problem with an example. Suppose we have matrix A:

A =

     1     0     1
     1     1     1
     0     1     1

和矩阵B:

B =

     1     1
     1     1

如何编写函数C = func(A, B)来检查A中是否存在B?
如果A中存在它,则该函数返回C = [0 0 0; 0 1 1; 0 1 1],如果不存在,则该函数返回C = [0 0 0; 0 0 0; 0 0 0];.

How do i write function C = func(A, B) to check if B exists in A or not?
If it exists in A, the function returns C = [0 0 0; 0 1 1; 0 1 1], and if it does not, the function returns C = [0 0 0; 0 0 0; 0 0 0];.

修改:
应该指出的是,如果A m -by- n ,并且B p -by- q ,然后总是 m > p p > q .


It should be mentioned that if A is m-by-n, and B is p-by-q, then m > p and p > q always.

谢谢.

推荐答案

最有效的要求是信号处理工具箱.然后,您可以简单地使用xcorr2().按照您的示例,以下应该可以工作:

The most efficient requires the signal processing toolbox. Then you can simply use xcorr2(). Following your example, the following should work:

C = xcorr2 (A, B);
[Row, Col] = find (C == max (C(:)));
%% these are not the coordinates for the center of the best match, you will
%% have to find where those really are
%% The best way to understand this is to strip the "padding"
row_shift = (size (B, 1) - 1)/2;
col_shift = (size (B, 2) - 1)/2;
C = C(1+row_shift:end-row_shift, 1+col_shift:end-col_shift)
[Row, Col] = find (C == max (C(:)));
if (B == A(Row-row_shift:Row+row_shift, Col-col_shift:Col+col_shift))
    disp ("B shows up in A");
endif

上面的代码看起来有些令人费解,因为我试图覆盖任何大小的输入(仍然只有奇数大小),但是应该可以.

The code above looks a bit convoluted because I'm trying to cover inputs of any size (still only odd sized) but should work.

如果您没有此工具箱,我想您可以使用

If you don't have this toolbox, I think you can use the Octave code for it which should require only small adjustments. Basically, the only three lines that matter follow (note that the code is under GPL):

[ma,na] = size(a);
[mb,nb] = size(b);
c = conv2 (a, conj (b (mb:-1:1, nb:-1:1)));

在Octave中,如果至少使用信号包1.2.0,则xcorr2还可以使用额外的选项"coeff"来计算归一化互相关.匹配完美时,其值为1,因此您可以使用以下方法简化此操作:

In Octave, if you are using at least the signal package 1.2.0, xcorr2 can also take an extra option "coeff" which calculates the normalized cross correlation. This will have a value of 1 when the match is perfect, so you can simplify this with:

C = xcorr2 (A, B, "coeff");
if (any (C(:) == 1)
    display ("B shows up in A");
endif

这篇关于Matlab如何找出矩阵是否在另一个矩阵中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆