Home > Net >  Identity matrix of 3 Dimensional matrix
Identity matrix of 3 Dimensional matrix

Time:01-01

Identity = array([[[1., 0., 0., 0.],
    [0., 1., 0., 0.],
    [0., 0., 1., 0.],
    [0., 0., 0., 1.]],

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

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

There is a task which wants me to create identity matrix in 3D.

I have made assumptions that the above is the identity matrix in 3D with the shape (3,4,4).

I have seen other variations of identity of 3D matrix which I didn't understand. Check this What's the best way to create a "3D identity matrix" in Numpy? for reference.

If I am right in my above assumption of identity matrix. Please assist me to construct the same with numpy.

CodePudding user response:

You can use np.identity() to generate an identity matrix and then use np.broadcast_to() to add the third dimension:

import numpy as np
n = 4
print(np.broadcast_to(np.identity(n), (3, n, n)))

CodePudding user response:

You can also use np.tile:

n = 4
k = 3
out = np.tile(np.identity(n), (k,1)).reshape(k,n,n)

Output:

[[[1. 0. 0. 0.]
  [0. 1. 0. 0.]
  [0. 0. 1. 0.]
  [0. 0. 0. 1.]]

 [[1. 0. 0. 0.]
  [0. 1. 0. 0.]
  [0. 0. 1. 0.]
  [0. 0. 0. 1.]]

 [[1. 0. 0. 0.]
  [0. 1. 0. 0.]
  [0. 0. 1. 0.]
  [0. 0. 0. 1.]]]
  • Related