0
$\begingroup$

I'm trying to make a list of functions by parts and then graph them. But I have troubles accessing a variable element in list G, how could I solve it?

G = {x^2, Sin[x], (x - \[Pi])^2}
Y = {}
xl = {{-2, 0}, {0, \[Pi]}, {\[Pi], \[Pi] + 2}}

For[i = 1, i <= 3, i++, 
 AppendTo[Y, Which[xl[[i, 1]] < x < xl[[i, 2]], G[[i]]]]
]

Plot[Y, {x, -3, 6}]
$\endgroup$

1 Answer 1

2
$\begingroup$

I think you want to plot this:

Plot[Piecewise[{{x^2, x < 0}, {Sin[x], x < \[Pi]}}, (x - \[Pi])^2], {x, -3, 6}]

which gives you:

enter image description here

I figured it out with Which:

G = {x^2, Sin[x], (x - \[Pi])^2}
xl = {{-2, 0}, {0, \[Pi]}, {\[Pi], \[Pi] + 2}}
Y = Flatten[Table[{xl[[i, 1]] < x < xl[[i, 2]], G[[i]]}, {i, 3}]]
Plot[Which @@ Y, {x, -3, 6}]

which gives a slightly different output:

enter image description here

$\endgroup$
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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