I have two 2-D matrices, and I want to multiply these two matrices to get a new matrix. The first matrix A has dimension 943 x 1682, and it is shown below:
[[ 5. 3. 4. ..., 0. 0. 0.]
[ 4. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
...,
[ 5. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 5. 0. ..., 0. 0. 0.]]
And another matrix B has dimension 1682 x 20, and shown below:
[[ 0. 0. 0. ..., 0. 0. 3. ]
[ 0. 0.57735027 0.57735027 ..., 0. 0. 3. ]
[ 0. 0. 0. ..., 0. 0. 1. ]
...,
[ 0. 0. 0. ..., 0. 0. 2. ]
[ 0. 0. 0. ..., 0. 0. 1. ]
[ 0. 0. 0. ..., 0. 0. 1. ]]
However, when I try A.dot(B), or np.matmul(A,B), I got a new matrix whose values are all nan, as shown below:
[[ nan nan nan ..., nan nan nan]
[ nan nan nan ..., nan nan nan]
[ nan nan nan ..., nan nan nan]
...,
[ nan nan nan ..., nan nan nan]
[ nan nan nan ..., nan nan nan]
[ nan nan nan ..., nan nan nan]]
I figure this might be a result of multiplying 0. But why would it return nan at every position? And how should I deal with this so that I can get numbers instead of nan?
Thank you very much for help!
A single nan column in the first matrix, and\or a single nan row in the second matrix, could cause this issue. A way to verify that indeed all values are valid in both matrices is to filter out the nans and see if the shape remains the same:
a_shape_before = A.shape
a_shape_after = A[numpy.logical_not(numpy.is_nan(A))].shape
assert a_shape_before == a_shape_after
And likewise for B.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With