Solving Ax=b with numpy linalg python raise LinAlgError('Incompatible dimensions')

I am trying to solve Ax = b for x.

A is a sparse matrix; x is unknown, and a b is a np.array.

print(type(matrix_a))
print(type(vector_c))

print("Matrix A Shape  -- %s " %str(matrix_a.shape))
print("vector c shape -- %s " %len(vector_c))

#xx = np.array([1],dtype=np.float32)

vec_c = np.insert(vector_c,0,1)
print("Update Vector c shape -- %s "% len(vec_c))

new_matrix = matrix_a.todense()
new_matrix_T = new_matrix.transpose()

x = np.linalg.lstsq(new_matrix_T,vec_c)

yields the following output.

Matrix A Shape -- (48002, 7651)
vector c shape -- 48001
Update Vector C shape -- 48002

Traceback (most recent call last): File

"/Users/removed/PycharmProjects/hw2/main.py", line 139, in main() File "/Users/removed/PycharmProjects/hw2/main.py", line 65, in main b1 = st.fit_parameters(A1, c) File "/Users/removed/PycharmProjects/hw2/hw3_part1.py", line 191, in fit_parameters x = np.linalg.lstsq(new_matrix_T,vec_c) File "/Users/removed/.conda/envs/hw2/lib/python3.6/site-packages/numpy/linalg/linalg.py", line 1984, in lstsq raise LinAlgError('Incompatible dimensions') numpy.linalg.linalg.LinAlgError: Incompatible dimensions

Upvotes: 1

Views: 3615

Answers (1)

FHTMitchell
FHTMitchell

Reputation: 12147

You're transposing your matrix matrix_a which is shape M, N = 48002, 7651 to shape N, M = 7651, 48002. But the problem is that your vector is shape M = 48002, and np.linalg.lstsq takes dimensions (a.shape=(M, N), b.shape=(M,). Because of your transpose, you are passing dimensions (a.shape=(N, M), b.shape=(M,)).

Solution? Don't transpose matrix_a.

Upvotes: 2

Related Questions