0
$\begingroup$

Apologies if this has been answered before but I can't find it.

My situation is I have a list of variable expressions and another list of what I want to equate each one to. And I want to combine these into conditionals which will go into Solve.

I'll use a code box to show what I mean with a trivial example - my real lists could be quite long.

variableExpressions = {a+b+c, a-b+c, a+b-c etc etc};
myCoefficients = {5, 7, 2, etc etc};

(* What I want to do is plug into solve like the following *)

Solve[a+b+c==5 && a-b+c==7 && a+b-c ==2 etc etc etc ,{a,b,c}, PositiveIntegers]

In a real case I may have quite many variable expressions and many what I call coefficients (possibly in the hundreds) to the point hand entering them is not feasible.

I'm sure someone knows how to do this or can reference where this has been done before.

Any help/ideas is much appreciated.

$\endgroup$

2 Answers 2

1
$\begingroup$

Method 1

variableExpressions = {a + b + c, a - b + c, a + b - c};
myCoefficients = {5, 7, 2};

sol =Solve[MapThread[Equal, {variableExpressions, myCoefficients}], 
 Variables@variableExpressions]

$\left\{\left\{a\to \frac{9}{2},b\to -1,c\to \frac{3}{2}\right\}\right\}$

You can solve using PositiveIntegers but the solution will be {} for this particular case.


Method 2

Since these are linear equations:

m = Last@Normal@
   CoefficientArrays[variableExpressions, 
    Variables@variableExpressions]

sol2 = Thread[
  Variables@variableExpressions -> LinearSolve[m, myCoefficients]]

$\left\{a\to \frac{9}{2},b\to -1,c\to \frac{3}{2}\right\}$


Check

MapThread[Equal, {variableExpressions, myCoefficients}] /. sol

{{True, True, True}}

$\endgroup$
1
  • $\begingroup$ Maybe I wasn't clear - I made that up as a simple example to indicate the process I wanted, I can solve that in my head. My question was how to combine two lists as mentioned to automatically create a list of conditionals which can then be place in Solve to save labour. But you have got that bit done - I should have figured that one myself to be honest - your help is much appreciated. $\endgroup$
    – ngc5139
    Commented Nov 13 at 18:30
1
$\begingroup$

If you have some scalar operator (in your case "Equal) that you want to apply on lists, you can do this with either "Thread" or "MapThread". E.g. your example:

variableExpressions = {a + b + c, a - b + c, a + b - c };
myCoefficients = {5, 7, 2};
Thread[variableExpressions == myCoefficients]

{a + b + c == 5, a - b + c == 7, a + b - c == 2}

Or with MapThread:

MapThread[Equal, {variableExpressions, myCoefficients}]

{a + b + c == 5, a - b + c == 7, a + b - c == 2}
$\endgroup$

Your Answer

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

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