based on this answer I was coding a simple class for symmetric matrices in python with numpy, but I'm having (probably a very simple) problem. This is the problematic code:
import numpy as np
class SyMatrix(np.ndarray):
def __init__(self, arr):
self = (arr + arr.T)/2.0 - np.diag(np.diag(arr))
def __setitem__(self,(i,j), val):
np.ndarray.__setitem__(self, (i, j), value)
np.ndarray.__setitem__(self, (j, i), value)
Besides this feeling wrong (I don't know if assigning to self
is a good practice...) When I try to create a new array I get this:
>>> foo = SyMatrix( np.zeros(shape = (2,2)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: only length-1 arrays can be converted to Python scalars
I also tried:
import numpy as np
class SyMatrix(np.ndarray):
def __init__(self, n):
self = np.zeros(shape = (n,n)).view(SyMatrix)
def __setitem__(self,(i,j), val):
np.ndarray.__setitem__(self, (i, j), value)
np.ndarray.__setitem__(self, (j, i), value)
And then I get:
>>> foo = SyMatrix(2)
>>> foo
SyMatrix([ 6.93581448e-310, 2.09933710e-316])
>>>
where I expected an array with shape=(2,2)
. What's the correct way to do what I'm trying to do? Is assigning to self
problematic?