Why this code doesn't work? Can anyone help me?
s = {1, 2, 3};
f[x_, s_] :=
Piecewise[
Table[{x + i, s[[i]] <= x <= s[[ i + 1]]}, {i, Length[s[1]] - 1}]]
Manipulate[Plot[f[x, s], {x, 0, 3}], {s[[1]], 0, 3}]
Why this code doesn't work? Can anyone help me?
s = {1, 2, 3};
f[x_, s_] :=
Piecewise[
Table[{x + i, s[[i]] <= x <= s[[ i + 1]]}, {i, Length[s[1]] - 1}]]
Manipulate[Plot[f[x, s], {x, 0, 3}], {s[[1]], 0, 3}]
Clear["Global`*"]
s = {1, 2, 3};
f[x_] = Piecewise[
Table[{x + i, s[[i]] <= x <= s[[i + 1]]}, {i, Length[s] - 1}]]
Plot[f[x], {x, 0, 3}]
EDIT:
Clear[f]
f[x_, s_] :=
Piecewise[
Table[{x + i, s[[i]] <= x <= s[[i + 1]]}, {i, Length[s] - 1}]]
Manipulate[
s = s0 + {1, 2, 3};
Column[{StringForm["`` = ``", HoldForm[f[x, s]], f[x, s]],
Plot[f[x, s], {x, s0, s0 + 3},
PlotRange -> {{0, 6}, {0, 9}},
PlotRangePadding -> Scaled[0.01],
ImageSize -> Medium]}],
{{s0, 0}, 0, 3, 0.05, Appearance -> "Labeled"}]
f
that varies and can be manipulated.
$\endgroup$
Commented
Feb 16, 2022 at 16:36
s
a fixed value and once defined, the definition of f
does not change. You would need to make the definition of s
variable. Alternatively, make f
dependent on another variable other than x
$\endgroup$
Commented
Feb 16, 2022 at 16:41
I'm making some guesses about what you want, but here's a line of thinking...
First off, your function f doesn't really depend on x, and by allowing x to be input as an argument will just open you up to errors and cause confusion. Let's start with this:
myPiecewise[intervals_List] :=
Function[x,
Piecewise[
Table[{x + i, intervals[[i]] <= x < intervals[[i + 1]]},
{i, Length[intervals] - 1}]]]
This will output a function that can just take a value, it doesn't require you to guarantee agreement of formal argument names.
Now let's bundle that into a Plot:
myPiecewisePlot[intervals_List] :=
Plot[myPiecewise[intervals][z],
{z, intervals[[1]], intervals[[-1]]}]
I used z to illustrate that we're no longer dependent on a particular name for the formal argument. Since I've hidden myPiecewise inside myPiecewisePlot, it actually doesn't really matter, but I still like it better. Notice that I'm assuming the plot should start and end with the first and last values of the list provided. That seemed like a reasonable assumption, but I don't know if it's what you want.
Now we're ready for Manipulate:
Manipulate[myPiecewisePlot[list], {{list, {0, 1, 2}}}]
You'll have to be careful to enter your value as a list. You may need to add some validation or coercion to this. Anyway, here's an example where I've changed the interval list.
Maybe similar with this result.
e = .1;
n = 5;
f[x_, k_] :=
Which @@ Flatten[Table[{i <= x < i + 1 - e, x + i}, {i, k, n}], 1]
Manipulate[
Plot[f[x, k], {x, 1, n}, ExclusionsStyle -> Red,
AxesOrigin -> {0, 0}], {k, 1, n - 1, 1}, ControlPlacement -> Top]