Home > Net >  Reshaping a matrix (numpy array) when matrices are multiplied on individual elements
Reshaping a matrix (numpy array) when matrices are multiplied on individual elements

Time:12-15

I am trying to multiply each element of a 2x2 matrix say [1,1],[1,1] with a 2x2 Identity matrix. The problem is that numpy puts the whole identity matrix as a separate sub index which is not the result I need to evaluate it further, I want it to have 4 rows and 4 columns but when I reshape it to (4,4), it offsets the values and I get [1,0,1,0] on each row (consult the image for required and obtained results). Thank you! Image here

CodePudding user response:

welcome to SO. For future questions, please try to put code here instead of linking an image, it would make things easier.

As for your question, you can achieve such a matrix with np.tile. Example:

import numpy as np
I = np.identity(2)
A = np.tile(I, [2, 2])

Content of A:

array([[1, 0, 1, 0],
       [0, 1, 0, 1],
       [1, 0, 1, 0],
       [0, 1, 0, 1]])

This is assuming that the matrix by which you want to multiply the identity is precisely [[1 1][1 1]] and not any 2x2 matrix (I did not completely understood this point of your question). If it can be other matrices, please provide examples of expected output as there might be several possible solutions.

Edit after your example of A = [2*I, 0*I],[4*(-I), 1*I]:

import numpy as np

# generate the tiled identity (see above)
M = np.tile(np.identity(2), [2, 2])

# now we choose which ones are going to be negatives, from your example:
V = np.array([[1, 1], [-1, 1]])

# now define the 2x2 input matrix
N = np.array([[2, 0], [4, 1]])

# finally, let's combine all this:
A = np.repeat(N * V, 4).reshape(-1, 4) * M

Content of A:

array([[ 2.,  0.,  2.,  0.],
       [ 0.,  0.,  0.,  0.],
       [-4., -0., -4., -0.],
       [ 0.,  1.,  0.,  1.]])

CodePudding user response:

Looks like you want the Kronecker product.

In [585]: np.kron(np.ones((2,2),int), np.eye(2,dtype=int))
Out[585]: 
array([[1, 0, 1, 0],
       [0, 1, 0, 1],
       [1, 0, 1, 0],
       [0, 1, 0, 1]])

You were try to make the array with repeated uses of the eye:

In [590]: np.array([I,I,I])
Out[590]: 
array([[[1, 0],
        [0, 1]],

       [[1, 0],
        [0, 1]],

       [[1, 0],
        [0, 1]]])

This is a (3,2,2), that's joining the eye on a new leading axis.

It is possible to transpose/reshape the (2,2,2,2) produced by np.array([[I,I],[I,I]]), but I'll you with the kron.

  • Related