pythonnumpylinear-equation

Solving Linear Equation Using NumPy


I am trying to solve linear equations 3x+6y+7z = 10, 2x+y+8y = 11 & x+3y+7z = 22 using Python and NumPy library.

import numpy as np
a = np.array([[3, 6, 7],
              [2, 1, 8],
              [1, 3, 7]])
b = np.array([[10, 11, 22]])
np.linalg.solve(a, b)

but can't figure out what am I doing wrong in the above code which is causing to throw out the following error

ValueError: solve: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (m,m),(m,n)->(m,n) (size 1 is different from 3)


Solution

  • Your b is a 1×3 array, so the dimensions of a and b do not match. Try

    1. b = np.array([[10], [11], [12]]) so that b is a 3×1 array, or

    2. b = np.array([10, 11, 12]) so that b is a vector with length 3 (which, as well as just b = [10, 11, 12], is also admissible by .solve(); see the doc).

    The former will result in a 3×1 array as the solution, whereas the latter will result in a vector of length 3. Probably it is better to use the latter; usually we don't really care whether a vector is a column vector or a row vector. NumPy usually handles vectors in reasonable ways.