-1

Here is an example code in Python:

import numpy as np

X = np.matrix([[0, 1], [1, 0]])
e1 = np.array([1, 1])

state = X @ e1
print(X @ state)

The matmul operand when doing a matrix vector multiplication returns the vector in the shape (2,1) instead of (2,), thus you cannot multiply the resulting vector by another matrix without having a mismatch.

To solve the error, I could use the reshape function after the multiplication to get the correct result. But, I was wondering if there was a way to directly have the correct shape, since I have to do a lot of operations of this kind inside a for loop.

1 Answers1

2

If you use np.array instead of np.matrix, it will solve your problem:

import numpy as np

X = np.array([[0, 1], [1, 0]])
e1 = np.array([1, 1])

state = X @ e1
print(state.shape)
# output: (2,)

print(X @ state)
# output: [1 1]

np.matrix is deprecated anyway:

It is no longer recommended to use this class, even for linear algebra. Instead use regular arrays. The class may be removed in the future.

Hope this will help!

Cythonista
  • 91
  • 7