I am using sympy to solve a system of equations Ax=B
and finding the matrix x
. x
is a 3 by 3 matrix, A
and B
are 3 by 4 matrices. The results are not numbers, but in the form of symbols. How can I obtain a numeric result?
Code:
import sympy as sp
X = sp.Matrix([[1,2,3,4],
[5,6,7,8],
[1,1,1,1]])
x = sp.Matrix([[5,6,7,8],
[1,2,3,4],
[1,1,1,1]])
a,b,c,d,e,f,g,h = sp.symbols('a,b,c,d,e,f,g,h')
M = sp.Matrix([[a,b,c],
[d,e,f],
[g,h,1]])
eq = solve(x-M.multiply(X),(a,b,c,d,e,f,g,h))
print(eq)
Output:
{a: c/4, b: 1 - c/4, d: f/4 + 1, e: -f/4, g: 0, h: 0}
The output of solve
seems to indicate that there are infinity many solutions, and that you can use c
and f
as free parameters. To see your full matrix, and choosing some values for c
and f
, you could use:
M.subs(eq).subs({c:1, f:2}).evalf()
Result:
Matrix([
[0.25, 0.75, 1.0],
[ 1.5, -0.5, 2.0],
[ 0, 0, 1.0]])
Here subs(eq)
fill in the solution. subs({c:44, f:28})
fills in some values for c
and f
. evalf()
creates a numerical result; this is needed when the expressions would contain fractions, square roots or other functions without evaluation.
For a more general approach, one could try to substitute all unassigned symbols with zero:
Ms = M.subs(eq)
Ms.subs({fr:0 for fr in Ms.free_symbols}).evalf()
Result:
Matrix([
[0, 1, 0],
[1, 0, 0],
[0, 0, 1]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.