- #1

- 95

- 2

## Summary:

- I'm creating a sparse matrix class and am stuck on how to update the attributes within the class.

## Main Question or Discussion Point

I'm working on a sparse matrix class, where I'm creating an internal representation of a random matrix a la CSR (Sparse Matrix). 'A' signifies the non-zero elements in the matrix, 'IA' are the rowpointers and 'JA' the column indices of the non-zero elements.

When I change a value in the input matrix, this is registered and updated in the attribute self._matrix. But neither A, IA, or JA are.

A should be equal to [9 5 8 3 6] and _number_of_nonzero should be equal to 5. IA and JA should then also change. How can I update self._A, self._IA and self._JA? I've been experimenting with setter and getter methods, but without success. Furthermore, I'm confused why self._matrix updates automatically.

Python:

```
import numpy as np
class SparseMatrix:
def __init__(self,Matrix):
if not isinstance(Matrix,np.ndarray):
raise TypeError('Matrix should be of type np.ndarray')
self._matrix=Matrix
#setting up an internal representation of CSR, A and JA
self._A=self._matrix[self._matrix!=0]
self._JA=np.nonzero(self._matrix)[1]
#IA
rowpointer=[0]
for i in range(self._matrix.shape[0]):
indices=len(np.nonzero(self._matrix[i])[0])
rowpointer.append(indices+rowpointer[i])
self._IA=np.asarray(rowpointer)
# more attributes
self._number_of_nonzero=len(np.nonzero(self._matrix)[0])
self.intern_represent='CSR'
def __repr__(self):
return 'A={}\nIA={}\nJA={}'.format(self._A,self._IA,self._JA)
```

Python:

```
d=np.array([[0,0,0,0],
[5,8,0,0],
[0,0,3,0],
[0,6,0,0]])
f=SparseMatrix(d)
f._matrix[0,0]=9 #change first element of matrix to 9
print(f._matrix)
print(f)
```

Code:

```
array([[9,0,0,0],
[5,8,0,0],
[0,0,3,0],
[0,6,0,0]])
A=[5 8 3 6]
IA=[0 0 2 3 4]
JA=[0 1 2 1]
4
```