2
$\begingroup$

A system of linear equations:

$\left\{\begin{aligned} x_{1}+3 x_{2}+x_{3} &=2 \\ 3 x_{1}+4 x_{2}+2 x_{3} &=9 \\-x_{1}-5 x_{2}+4 x_{3} &=10 \\ 2 x_{1}+7 x_{2}+x_{3} &=1 \end{aligned}\right.$

I know how to get its coefficient matrix.

Clear["Global`*"];
eqns = {\!\(TraditionalForm\`
\*SubscriptBox[\(x\), \(1\)] + 3 
\*SubscriptBox[\(x\), \(2\)] + 
\*SubscriptBox[\(x\), \(3\)]\[AlignmentMarker] == 
      2\), \!\(TraditionalForm\`3 
\*SubscriptBox[\(x\), \(1\)] + 4 
\*SubscriptBox[\(x\), \(2\)] + 2 
\*SubscriptBox[\(x\), \(3\)]\[AlignmentMarker] == 
      9\), \!\(TraditionalForm\`\(\[Minus]
\*SubscriptBox[\(x\), \(1\)]\) \[Minus] 5 
\*SubscriptBox[\(x\), \(2\)] + 4 
\*SubscriptBox[\(x\), \(3\)]\[AlignmentMarker] == 
      10\), \!\(TraditionalForm\`2 
\*SubscriptBox[\(x\), \(1\)] + 7 
\*SubscriptBox[\(x\), \(2\)] + 
\*SubscriptBox[\(x\), \(3\)]\[AlignmentMarker] == 1\)};
c = CoefficientArrays[eqns, Variables@eqns];
mc = MatrixForm@c[[2]]

$\left(\begin{array}{ccc}1 & 3 & 1 \\ 3 & 4 & 2 \\ -1 & -5 & 4 \\ 2 & 7 & 1\end{array}\right)$

How to get the list of constant terms of these linear equations, i.e {2,9,10,1}?

$\endgroup$
5
  • 2
    $\begingroup$ eqns[[All, -1]]? $\endgroup$
    – kglr
    Mar 23, 2022 at 3:12
  • $\begingroup$ @bmf, I get {2, 9, 10, 1} both in version 11.3 (Windows 64b) and in version 13.0.0 (Wolfram Cloud) $\endgroup$
    – kglr
    Mar 23, 2022 at 3:19
  • $\begingroup$ @kglr Thank you! It's work. Another question, what if the constant term is not written on the same side of the equal sign? For example, constant terms are mixed with variable terms. Is there a more general method? $\endgroup$
    – lotus2019
    Mar 23, 2022 at 3:24
  • $\begingroup$ @kglr I know. there were some other lines that caused some confusion, and hence I deleted. sorry about that $\endgroup$
    – bmf
    Mar 23, 2022 at 3:26
  • $\begingroup$ I'm confused. You already know CoefficientArrays, why are you still having difficulty in obtaining the list of constant terms? Or you just obtain this code sample from somewhere without understanding it? $\endgroup$
    – xzczd
    Mar 24, 2022 at 11:04

1 Answer 1

8
$\begingroup$

Try this:

Part[-Normal[CoefficientArrays[eqns]], 1]
(*{2, 9, 10, 1}*)

The system coefficients:

Part[Normal[CoefficientArrays[eqns]], 2]
(*{{1, 3, 1}, {3, 4, 2}, {-1, -5, 4}, {2, 7, 1}}*)
$\endgroup$
3
  • 1
    $\begingroup$ (+1) nice approach!!! $\endgroup$
    – bmf
    Mar 23, 2022 at 3:35
  • 1
    $\begingroup$ I found this approach useful for some uses of LinearSolve. Greetings, bmf! $\endgroup$ Mar 23, 2022 at 3:40
  • 1
    $\begingroup$ Nice approach! Thank you! $\endgroup$
    – lotus2019
    Mar 23, 2022 at 10:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.