Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a matrix from the coefficients of equations

Given the equations

eqn1 = 5 x1 + 2 x2 + 3 x3 == 8
eqn2 = 4 x1 + 7 x2 + 9 x3 == 5
eqn3 = 6 x1 +   x2 + 9 x3 == 2

how do I extract the coefficients of x1, x2, x3 to form a matrix?

I tried using CoefficientArrays but the output was given as a SparseArray.

like image 734
penny Avatar asked Sep 16 '11 10:09

penny


2 Answers

Try Normal

(Normal[CoefficientArrays[{eqn1, eqn2, eqn3}, {x1, x2, x3}]][[2]]) // MatrixForm

enter image description here

like image 163
Nasser Avatar answered Oct 04 '22 00:10

Nasser


I am not fond of Normal

Coefficient[# /. Equal[e_, _] -> e, {x1, x2, x3}] & /@ {eqn1, eqn2, eqn3}

Shorter but not as clear:

Coefficient[First@#, {x1, x2, x3}] & /@ {eqn1, eqn2, eqn3}
like image 44
Dr. belisarius Avatar answered Oct 04 '22 01:10

Dr. belisarius