3
$\begingroup$

After solving a function I get a list as a set of rules. {{x -> 0}, {x -> 0, x -> 10.}, {x -> 0, x -> 5.}, {x -> 0, x -> 3.33333}, {x -> 0, x -> 2.5}, {x -> 0, x -> 2.}, {x -> 0, x -> 1.66667}, {x -> 0, x -> 1.42857}, {x -> 0, x -> 1.25}, {x -> 0,x -> 1.11111}, {x -> 0, x -> 1.}. The first entry in the list has a single rule while the all other entries have 2 rules. It might be possible that some entries have 3 rules also. What I need to do is replace all the rules by its values. So the resulting list should be like {{0},{0,10},...}. These are like values of y. Values of x are Range[0,1,0.1].

To plot them, if I had list of numbers rather than a list of rules I could first extract first list as listy1 = y[[;;,1]]; listy2 = y[[;;,2]]; p1 = ListLinePlot[]; p2 = ListLinePlot[]; Show[p1,p2] . This also has a issue that whenever I will run a command list2 = y[[;;,2]], it will fail because the second element of first row does not exist.

Please tell how to do deal with these problems.

$\endgroup$

1 Answer 1

2
$\begingroup$
rules = {{x -> 0}, {x -> 0, x -> 10.}, {x -> 0, x -> 5.}, {x -> 0, 
    x -> 3.33333}, {x -> 0, x -> 2.5}, {x -> 0, x -> 2.}, {x -> 0, 
    x -> 1.66667}, {x -> 0, x -> 1.42857}, {x -> 0, 
    x -> 1.25}, {x -> 0, x -> 1.11111}, {x -> 0, x -> 1.}};

You can use Values:

y = Values[rules]
{{0}, {0, 10.}, {0, 5.}, {0, 3.33333}, {0, 2.5}, {0, 2.}, {0, 1.66667}, 
 {0, 1.42857}, {0, 1.25}, {0, 1.11111}, {0, 1.}}

Use PadRight to inject a non-numeric value (say, Null) on the right for rows with fewer columns than the longest row:

ypadded = PadRight[y, Automatic, Null]
 {{0, Null}, {0, 10.}, {0, 5.}, {0, 3.33333}, {0, 2.5}, {0, 2.}, 
  {0, 1.66667}, { 0, 1.42857}, {0, 1.25}, {0, 1.11111}, {0, 1.}}
listy1 = ypadded[[;;, 1];

listy2 = ypadded[[;;, 2]]; 

p1 = ListLinePlot[listy1, DataRange -> {0, 1}, PlotStyle -> Red]; 

p2 = ListLinePlot[listy2, DataRange -> {0, 1}, PlotStyle -> Green];

Show[p1, p2, PlotRange -> All]

enter image description here

You can use a single ListLinePlot using Transpose @ ypadded as input:

ListLinePlot[Transpose @ ypadded, DataRange -> {0, 1}]

enter image description here

$\endgroup$
4
  • $\begingroup$ Can you also tell about the second issue? $\endgroup$
    – A Q
    Commented Mar 28, 2021 at 7:24
  • $\begingroup$ @AQ, please see the update. $\endgroup$
    – kglr
    Commented Mar 28, 2021 at 7:39
  • $\begingroup$ Is there a way to plot the ypadded directly rather than extracting each and every column from it and then plotting it. $\endgroup$
    – A Q
    Commented Mar 28, 2021 at 7:51
  • $\begingroup$ @AQ, use ListLinePlot[Transpose@ypadded, DataRange -> {0, 1}] $\endgroup$
    – kglr
    Commented Mar 28, 2021 at 7:54

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.