I'm working on FEM analysis. I just wanted to evaluate a simple matrix multiplication and see the numeric result. How can I see the elements of the sparse matrix?
the code that I have used for is:
U_h= 0.5 * np.dot(np.dot(U[np.newaxis], K), U[np.newaxis].T)
Since U is a 1x3 matrix, K is 3x3 matrix and U.T is 3x1 matrix, I expect a 1x1 matrix with a single number in it. However, the result is "[[<3x3 sparse matrix of type 'class 'numpy.float64' with 3 stored elements in Compressed Sparse Row format>]]"
In [260]: M = sparse.random(5,5,.2, format='csr')
What you got was the repr
format of the matrix:
In [261]: M
Out[261]:
<5x5 sparse matrix of type '<class 'numpy.float64'>'
with 5 stored elements in Compressed Sparse Row format>
In [262]: repr(M)
Out[262]: "<5x5 sparse matrix of type '<class 'numpy.float64'>'\n\twith 5 stored elements in Compressed Sparse Row format>"
The str
format used print is:
In [263]: print(M)
(1, 0) 0.7152749140462651
(1, 1) 0.4298096228326874
(1, 3) 0.8148327301300698
(4, 0) 0.23366934073409018
(4, 3) 0.6117499168861333
In [264]: str(M)
Out[264]: ' (1, 0)\t0.7152749140462651\n (1, 1)\t0.4298096228326874\n (1, 3)\t0.8148327301300698\n (4, 0)\t0.23366934073409018\n (4, 3)\t0.6117499168861333'
If the matrix isn't big, displaying it as a dense array is nice. M.toarray()
does that, or for short:
In [265]: M.A
Out[265]:
array([[0. , 0. , 0. , 0. , 0. ],
[0.71527491, 0.42980962, 0. , 0.81483273, 0. ],
[0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. ],
[0.23366934, 0. , 0. , 0.61174992, 0. ]])