如何相交两个或多个矩阵? [英] How to intersect two or more matrices?

查看:237
本文介绍了如何相交两个或多个矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一些带有非负条目的矩阵,例如N个相等大小的MxM矩阵.例如,我有3个矩阵,如下所示:

Let say I have some number of matrices with non-negative entries, N matrices for example of equal sizes MxM. For example, I have 3 matrices as follow:

A1=[2, 2, 0;
    2, 2, 0;
    0, 2, 0];


A2=[4, 0, 4;
    4, 3, 0;
    0, 0, 1];


A3=[2, 0, 0;
    1, 0, 3;
    3, 4, 3];

我想在matlab中找到A1,A2和A3的交集.这意味着我想获得以下矩阵:

I want to find the intersection of A1, A2, and A3 in matlab. That means I want to get the follow matrix:

 B=[-1,  2,  4;
    -1, -1,  3;
     3, -1, -1];

如果N个矩阵的(i,j)元素(即元素A1(i,j),A2(i,j),A3(i,j))的交集最多为一个非零数那么B(i,j)等于那个数字.否则,如果交集至少为两个数字,我将输出-1,如上例所示.

If the intersection of the (i, j) element of the N matrices, i.e., the elements A1(i, j), A2(i, j), A3(i, j), is at most one nonzero number then B(i,j) equals that number. Else if the intersection is at least two numbers I output -1 as I showed in the previous example.

如何在不带循环的matlab中做到这一点?

How can I do this in matlab without loops?

推荐答案

首先,连接到单个3D矩阵:

First, concatenate to a single 3D-Matrix:

A=cat(3,A1,A2,A3)

然后计算非零元素,从而给出-1 -Elements的位置:

Then count the non-zero elements, which gives the location of the -1-Elements:

L=(sum(A~=0,3)>1)

最后,在L = 1的地方我们想要一个-1,否则我们想要那个位置上的单个元素,这是总和,因为其他元素为零:

Finally, There where L=1 we want a -1, otherwise we want the single element at that location, which is the sum because the others are zero:

L*-1+(1-L).*sum(A,3)

这篇关于如何相交两个或多个矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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