Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy Matrix operation without copying

Tags:

python

numpy

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 beneficial to do that?

like image 868
user14416 Avatar asked Feb 22 '26 19:02

user14416


1 Answers

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)
like image 155
bogatron Avatar answered Feb 24 '26 09:02

bogatron