从块构建矩阵 [英] build matrix from blocks

查看:157
本文介绍了从块构建矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用两个量A和B来描述的对象(实际上,它们可以大于两个).对象的相关性取决于A和B的值.尤其是我知道A和B的相关矩阵.例如:

I have an object which is described by two quantities, A and B (in real case they can be more than two). Objects are correlated depending on the value of A and B. In particular I know the correlation matrix for A and for B. Just as example:

a = np.array([[1, 1, 0, 0],
              [1, 1, 0, 0],
              [0, 0, 1, 1],
              [0, 0, 1, 1]])
b = np.array([[1, 1, 0],
              [1, 1, 1],
              [0, 1, 1]])
na = a.shape[0]
nb = b.shape[0]

与A的相关性:

因此,如果一个元素的A == 0.5而另一个等于A == 1.5,则它们是完全相关的(红色).否则,如果一个元素的A == 0.5而第二个元素的A == 3.5,则它们是不相关的(蓝色).

so if an element has A == 0.5 and the other equal to A == 1.5 they are fully correlated (red). Otherwise if an element has A == 0.5 and the second item has A == 3.5 they are uncorrelated (blue).

与B类似:

现在,我想将两个相关矩阵相乘,但我想获得一个具有两个轴的矩阵作为最终矩阵,其中新轴是原始轴的折叠版本:

Now I want multiply the two correlation matrixes, but I want to obtain as final matrix a matrix with two axis, where the new axes are a folded version of the original axes:

def get_folded_bin(ia, ib):
    return ia * nb + ib

这是我在做什么:

result = np.swapaxes(np.tensordot(a, b, axes=0), 1, 2).reshape(na* nb, na * nb)

视觉上:

特别是必须满足以下条件:

and in particular this must hold:

for ia1 in xrange(na):
    for ia2 in xrange(na):
        for ib1 in xrange(nb):
            for ib2 in xrange(nb):
                assert(a[ia1, ia2] * b[ib1, ib2] == result[get_folded_bin(ia1, ib1), get_folded_bin(ia2, ib2)])

实际上,我的问题是采用一般方式来处理更多数量(A,B,C,...).也许numpy中还有一个更简单的函数可以做到这一点.

actually my problem is to do it with more quantities (A, B, C, ...) in a general way. Maybe there is also a simpler function within numpy to do that.

推荐答案

我想终于找到了解决方案:

I think finally I have found a solution:

np.kron(a,b)

然后我就可以撰写

np.kron(np.kron(a,b), c)

这篇关于从块构建矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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