Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

For example I want to find solution with maximum value among solutions (and possibly plot it):

answers = Piecewise[List @@@ Last @@@ N @Solve[{
       z == 40 x + 50 y,
       6 x + 10 y <= 672,
       0.25 x + 0.15 y <= 24,
       1.5 y <= 42,
       0 <= x,
       0 <= y
       }, {z}, Integers]]

In this case it is : {4230.,x\[LongEqual]87.\[And]y\[LongEqual]15.}

share|improve this question

3 Answers 3

up vote 4 down vote accepted

I'm not sure why you are using piecewice to hold the answers, but you could just use sort and get the last element:

 answers = 
  List @@@ Last @@@ 
  N@Solve[{z == 40 x + 50 y, 6 x + 10 y <= 672, 
  0.25 x + 0.15 y <= 24, 1.5 y <= 42, 0 <= x, 0 <= y}, {z}, 
  Integers]

 Sort[answers][[-1]]

 (*=> *) {4230., x == 87. && y == 15.}

As for plotting the solution points, you could turn the conditional expressions into individual points and plot those using ListPlot3D:

 zxy = answers //. {{a_, Or[b_, c_]} :> Sequence[{a, b}, {a, c}] , 
 And -> Sequence, Equal[_, b_] :> b};

 ListPlot3D[zxy[[1 ;;, {2, 3, 1}]], AxesLabel -> {"x", "y", "z"} ]

This doesn't work for arbitrary answer lists, but works in your case. If you have results with different logic constructs you can modify the replacement rules accordingly.

Output from ListPlot3D showing the solutions

share|improve this answer
 answers[[1, -1]]
 (* {4230., x == 87. && y == 15.}   *)

EDIT: An alternative series of replacements to get the data for plotting:

pltdata =  (List @@@ Last @@@ N@
     Solve[{z == 40 x + 50 y, 6 x + 10 y <= 672, 
       0.25 x + 0.15 y <= 24, 1.5 y <= 42, 0 <= x, 0 <= y}, {z}, Integers] /.
  {And -> List, Or -> List, Equal[_, a_] :> a} //
  If[Depth[#] == 3, Reverse[#], Sequence @@ Reverse /@ Thread[#, List, 2]] & /@ # &) /.
  {{a_, b_}, c_} :> {a, b, c};

ListPointPlot3D[pltdata, ColorFunction -> (Hue[#3] &), BoxRatios -> 1]

enter image description here

share|improve this answer

Could use Maximize.

Maximize[{z, z == 40*x + 50*y,
       6 x + 10 y <= 672,
       x/4 + 3*y/20 <= 24,
       3*y/2 <= 42,
       0 <= x,
       0 <= y}, {x,y,z}, Integers]

(* {4230, {x -> 87, y -> 15, z -> 4230}} *)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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