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?
2 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)

- 18,639
- 6
- 53
- 47
-
1Good answer, just a tiny note. `aa = numpy.dot(a, a, out=a)` doesn't work (on linux with numpy 1.6). I've always had trouble using `np.dot(..., out=x)` when `x` is one of the arguments to `np.dot`. Your answer however is correct for just about any other numpy function I can think of, I'm not sure why `np.dot` is special. Maybe someone else can address that point. – Bi Rico May 06 '13 at 21:49
-
Interesting. Perhaps it is a version issue. I ran the command as shown above on Red Hat Linux 6.3 and it worked for me (I don't recall the numpy version off hand but I will check). It also works for me on OS X 10.6 with numpy 1.7. – bogatron May 07 '13 at 03:33
-
Curious, do you mind trying `a = np.ones((4, 4)); np.dot(a, a, out=a); print a` and telling me what you get? – Bi Rico May 07 '13 at 03:37
-
Just looked a the result on OS X and - surprisingly - the output is all zeros. Thanks for pointing this out. I've amended my answer to write the result to a different array. I will try this on RHEL 6.3 tomorrow and let you know what I get there as well. – bogatron May 07 '13 at 03:54
-
The output was also all zeros on RHEL with numpy 1.6.2. If I had to guess, I'd guess that the output array is being zero-filled prior to accumulating the row/column products but since the output is one of the inputs, the result is always identically zero. I did verify that `np.add(a, a, out=a)` does produce the expected output. – bogatron May 07 '13 at 13:30
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.