Build a matrix of blocks

I have an object that is described by two values: A and B (in the real case, there can be more than two). Objects are correlated depending on the values ​​of A and B. In particular, I know the correlation matrix for A and for B. As an 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]

correlation for A:

correlation A

therefore, if an element has A == 0.5, and the other is A == 1.5, they are fully correlated (red). Otherwise, if the element has A == 0.5, and the second element has A == 3.5, they are uncorrelated (blue).

Similarly for B:

correlation B

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

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

that's what I'm doing:

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

visually:

enter image description here

and, in particular, this should be done:

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 .

0
2

, , :

np.kron(a,b)

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

np.einsum tensordot:

result = np.einsum('ij,kl->ikjl',a,b).reshape(-1, na * nb)

, reshape.

, einsum.

0

All Articles