5
$\begingroup$

Assume that I want to solve a simultaneous equation below.

\begin{cases} 2x_1+3x_2=5\\ x_1-x_2=0 \end{cases}

First I construct two lists

coefs = {{2, 3, 5}, {1, -1, 0}};
vars = Array[x, 2];

Note that I feel more comfortable to put the constants 5 and 0 in the coefficient list rather than separating them into another list.

Because I don't know how to construct equ from the above lists, I manually construct as follows.

equ = 2 x[1] + 3 x[2] == 5 && x[1] - x[2] == 0

Finally equ is passed to Solve[equ, vars].

Question

What is the simplest way to construct equ from the available two list coefs and vars?

Minimal Working Example

The following template will save your typing time.

coefs = {{2, 3, 5}, {1, -1, 0}};
vars = Array[x, 2];
equ = 2 x[1] + 3 x[2] == 5 && x[1] - x[2] == 0
Solve[equ, vars]

1st attempt

coefs = {{2, 3, 5}, {1, -1, 0}};
vars = Array[x, 2];
temp1 = {#1, #2} & @@@ coefs.vars
temp2 = Table[temp1[[i]] == coefs[[i, 3]], {i, 1, 2}]
equ = temp2[[1]] && temp2[[2]]
Solve[equ, vars]

I also want to know what is the best way to concatenate temp2 in equ = temp2[[1]] && temp2[[2]].

$\endgroup$
0

3 Answers 3

7
$\begingroup$
coefs = {{2, 3, 5}, {1, -1, 0}};

Two additional approaches:

1. Using the fourth argument of Array to do all in a single step:

ClearAll[slv]
slv[a_] := Array[x, Length @ a, 1, Solve[Thread[a. {##, -1} == 0], {##}] &]

slv @ coefs

{{x[1] -> 1, x[2] -> 1}}

2. Process coefs directly into input for LinearProgramming:

ClearAll[lp]
lp[a_] := LinearProgramming[ConstantArray[0, Length@a], Most /@ a, Thread[{Last /@ a, 0}]]

lp @ coefs

{1, 1}

$\endgroup$
6
$\begingroup$

One way might be

 eqs = And @@ Thread[coefs[[1 ;; 2, 1 ;; 2]].vars == coefs[[All, 3]]]

Mathematica graphics

Applying it

coefs = {{2, 3, 5}, {1, -1, 0}};
vars = Array[x, 2];
equ = And @@ Thread[coefs[[1 ;; 2, 1 ;; 2]].vars == coefs[[All, 3]]];
Solve[equ, vars]

Mathematica graphics

$\endgroup$
5
$\begingroup$

If you need to see the equations, use

equ = Thread[coefs.Append[vars, -1] == 0]

Or, just go straight to the solution

Solve[Thread[coefs.Append[vars, -1] == 0], vars]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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