# [sympy] Re: Solving for a matrix?

```You have 4 equations with 16 unknowns, so there are going to be a lot of
solutions. ```
```
Many SymPy functions struggle with M[i, j] construction which creates
MatrixElement instead of an ordinary Symbol. I would use a Matrix filled
with Symbols:

M = sp.Matrix(sp.symarray('M', (4, 4)))
sp.solve(a - M*b, list(M))

This returns

{M_3_0: (-M_3_1*(a0 + a1 + a2 + a3) - M_3_2*a1 - M_3_3*(a1 + 2*a2 + 3*a3) +
a0)/a0, M_2_0: (-M_2_1*(a0 + a1 + a2 + a3) - M_2_2*a1 - M_2_3*(a1 + 2*a2 + 3
*a3) + a1)/a0, M_1_0: (-M_1_1*(a0 + a1 + a2 + a3) - M_1_2*a1 - M_1_3*(a1 + 2
*a2 + 3*a3) + a2)/a0, M_0_0: (-M_0_1*(a0 + a1 + a2 + a3) - M_0_2*a1 - M_0_3
*(a1 + 2*a2 + 3*a3) + a3)/a0}

which, as previously mentioned, is a lot of solutions. You can plug in some
arbitrary numbers for the free variables here.

On Saturday, March 10, 2018 at 7:38:00 AM UTC-5, Matthias Geier wrote:
>
> Dear list.
>
> I have this equation:
>
>     a = M * b,
>
> where a and b are column vectors and M is a 4x4 matrix.
> a and b consist of quite simple expressions, M is unknown:
>
> >>> import sympy as sp
> >>> a0, a1, a2, a3 = sp.symbols('a:4')
> >>> a = sp.Matrix([a3, a2, a1, a0])
> >>> b = sp.Matrix([a0, a3 + a2 + a1 + a0, a1, 3 * a3 + 2 * a2 + a1])
> >>> M = sp.MatrixSymbol('M', 4, 4)
> >>> sp.Eq(a, M * b)
> Eq(Matrix([[a3], [a2], [a1], [a0]]), M*Matrix([
> [               a0],
> [a0 + a1 + a2 + a3],
> [               a1],
> [ a1 + 2*a2 + 3*a3]]))
>
> What's the most straightforward way to solve this for M?
>
> I have actually found a way, but it seems a bit non-obvious to me:
>
> >>> def get_value(i, j):
> ...     return b[i].as_coefficients_dict()[a[j]]
> ...
> >>> M_inv = sp.Matrix(4, 4, get_value)
> >>> M_inv.inv()
> Matrix([
> [ 2, -2,  1,  1],
> [-3,  3, -2, -1],
> [ 0,  0,  1,  0],
> [ 1,  0,  0,  0]])
>
> This is the solution I'm looking for, but I was hoping there is a
> better way to get it.
> Also, the way I did it I had to know that I could look for the inverse
> and then undo the inverse afterwards, but I would prefer if there is a
> solution without this manual step.
>
>
> cheers,
> Matthias
>

--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email