4
$\begingroup$

I have a function eqsfromMatrix[..] that generates linear equations from a matrix which I would like to plot but there seems to be no direct way to plot them. I think I should probably solve for one of the variables before attempting to plot them but do not know how to manipulate them. I've tried everything from Plot[...] to Graphics[...] but they rendered very poorly. One would think there would be a straightforward or direct way to plot 3 linear equations but it eludes me for now. My goal is to plot the lines formed from matrix and show where they intersect if there is a solution. Below in the code I have 3 matrices of 2, 3, 4 dimensions which I would like to plot if at all possible.

eqsfromMatrix[mat_, b_ : None, piv_ : "x"] := 
 Block[{len, abc, pivot, diff, vars, scals, eqs},
  len = Length[mat];
  abc = Alphabet[];
  pivot = Flatten[Position[abc, piv]][[1]]; 
  start[m_] := pivot /; len <= 26 - pivot + 1;
  start[m_] := 26 - len + 1;
  end[m_] = start[m] + len - 1;
  vars = Take[abc, {start[m], end[m]}];
  eqs = mat.vars;
  scals = 
   Switch[b, None, Return[eqs], _List, b, 1, Take[abc, {1, len}], 0, 
    Table[0, len]];
  Table[eqs[[i]] == scals[[i]], {i, 1, len}]
  ]
(*m={{1,0,1,3},{-1,3,2,1},{3,2,4,5},{8,3,5,3}};
b={-1,3,2,4};*)
(*m={{1,0,1},{-1,3,1},{3,4,5}};
b={3,2,4};*)
m = {{1, 2}, {3, 2}};
b = {1, -2};
sol = LinearSolve[m, b]
eqs = eqsfromMatrix[m, b]
eqs[[1]] // Expand
Solve[eqs[[1]], y]

Plot[eqsfromMatrix[m, b], {x, -1, 1}]
$\endgroup$
1
  • 1
    $\begingroup$ You mean ContourPlot and ContourPlot3D? I don't think there's an easy way for 4D, though. BTW your code can be simplified to ContourPlot[Thread[m.{x, y} == b] // Evaluate, {x, -2, 2}, {y, -2, 2}]. $\endgroup$
    – xzczd
    Commented Jun 15, 2020 at 4:46

1 Answer 1

9
$\begingroup$

For 2 or 3 dimensions:

Clear["Global`*"]

eqnsFromMatrix[m_?MatrixQ, b_?VectorQ] := Block[
  {x, n = Length@m, var, eqns, pt = LinearSolve[m, b], min, max, plt, 
   grph},
  min = Floor@Min@pt;
  max = Ceiling@Max@pt;
  var = Array[x, n];
  eqns = Thread[m.var == b];
  plt = If[n == 2, ContourPlot, ContourPlot3D];
  grph = If[n == 2, Graphics, Graphics3D];
  Column[{
    Column@(eqns /. x[k_] :> Subscript[x, k]),
    Show[
     plt[Evaluate@eqns, 
      Evaluate[Sequence @@ Thread[{var, min, max}]],
      ImageSize -> Medium],
     grph[{Red, AbsolutePointSize[8],
       Tooltip[Point[pt], pt]}]]}]]

eqnsFromMatrix[{{1, 2}, {3, 2}}, {1, -2}]

enter image description here

eqnsFromMatrix[{{1, 0, 1}, {-1, 3, 1}, {3, 4, 5}}, {3, 2, 4}]

enter image description here

$\endgroup$
1
  • $\begingroup$ thank you so much. i had been struggling with this all day. $\endgroup$ Commented Jun 15, 2020 at 8:44

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.