Skip to content Skip to sidebar Skip to footer

NumPy Matrix Operation Without Copying

How I can make, for example, matrix transpose, without making a copy of matrix object? As well, as other matrix operations ( subtract a matrix from the matrix, ...). Is it benefici

Solution 1:

Taking the transpose of an array does not make a copy:

>>> a = np.arange(9).reshape(3,3)
>>> b = np.transpose(a)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> b
array([[0, 3, 6],
       [1, 4, 7],
       [2, 5, 8]])
>>> b[0,1] = 100
>>> b
array([[  0, 100,   6],
       [  1,   4,   7],
       [  2,   5,   8]])
>>> a
array([[  0,   1,   2],
       [100,   4,   5],
       [  6,   7,   8]])

The same applies to a numpy.matrix object.

This can be beneficial when you want to avoid unnecessarily consuming a lot of memory by copying very large arrays. But you also have to be careful to avoid unintentionally modifying the original array (if you still need it) when you modify the transpose.

A number of numpy functions accept an optional "out" keyword (e.g., numpy.dot) to write the output to an existing array. For example, to take the matrix product of a with itself and write the output an existing array c:

numpy.dot(a, a, out=c)

Solution 2:

Transpose operation as in b = a.T creates a shallow copy. a and b will share the same data.

For arithmetic operations see: - vs -= operators with numpy

Shallow copies are good for using the memory efficiently. However you have to keep in mind that changing a value will affect all copies.


Post a Comment for "NumPy Matrix Operation Without Copying"