Reputation: 33
I need to work with copys of matrices inside functions. But the copy of a (n x 1) matrix (vector) doesn't behave like it should.
Here I made an example:
Transpose of x multiplied with y gives me a normal vector-multiplication with an outcome of a (1x1)-matrix.
The copys a and b of x and y won't do that. They give back an array with dimension (n x n). What am I doing wrong here? And how could I avoid that?
>>>import numpy as np
>>>x=np.matrix('1;2;3')
>>>y=np.matrix('1;1;-1')
>>>x.T*y
matrix([[0]])
>>>a=np.copy(x)
>>>b=np.copy(y)
>>>a.T*b
array([[ 1, 2, 3],
[ 1, 2, 3],
[-1, -2, -3]])
Upvotes: 2
Views: 5747
Reputation: 23196
If you wish to copy a matrix, then instead of using numpy.copy
, use the copy
method on matrix
.
>>> x = np.matrix('1;3;3')
>>> x.copy()
matrix([[1],
[3],
[3]])
Another alternative is to use numpy.array(x, copy=True, subok=True)
.
Note that numpy.copy
is simply an alias for numpy.array(x, copy=True)
, and this causes downcasting of the input.
Upvotes: -1
Reputation: 231425
Your original arrays are of subclass matrix
. The copy is the base array
class. Use x.copy()
, the copy method specific to the matrix class to make another matrix. Then the matrix multiplication operations will work as before.
In [52]: x=np.matrix('1;3;3')
In [53]: x
Out[53]:
matrix([[1],
[3],
[3]])
In [54]: np.copy(x)
Out[54]:
array([[1],
[3],
[3]])
In [55]: x.copy()
Out[55]:
matrix([[1],
[3],
[3]])
The solution proposed in the other answer is to replace the matrix
multiplications with the equivalent ones for np.array
(np.dot
).
Upvotes: 3