3
$\begingroup$

I want to combine plot of four piecewise function for the following for. I have a code with "For", and I do not know which 'Show' can help me.

n = 4;
x[0] = 0;
x[n] = 1;
Do[x[L + 1] = N[x[L] + 1, 1];, {L, 0, 1}]
Subscript[A, 0][x_] = 
         Piecewise[{{1 - (x - x[0])/(x[1] - x[0]), x[0] <= x <= x[1]}}]
            For[k = 0, k < n - 1, k++; 
             Print[Subscript[A, k][x_] = 
               Piecewise[{{(x - x[k - 1])/(x[k] - x[k - 1]), 
                  x[k - 1] <= x <= x[k]}, {1 - (x - x[k])/(x[k + 1] - x[k]), 
                  x[k] <= x <= x[k + 1]}}]]]

Any suggestion?

$\endgroup$

1 Answer 1

0
$\begingroup$

I think you are trying to do something like the following:

ClearAll[x]
n = 4;
x[0] = 0;
x[n] = 1;
Do[x[L + 1] = x[L] + 1;, {L, 0, 2}];
x /@ {0, 1, 2, 3, 4}

{0, 1, 2, 3, 1}

ClearAll[aa]
aa[0][y_] :=  Piecewise[{{1 - (y - x[0])/(x[1] - x[0]), x[0] <= y <= x[1]}}]
aa[k_][y_] := Piecewise[{{(y - x[k - 1])/(x[k] - x[k - 1]), x[k - 1] <= y <= x[k]}, 
    {1 - (y - x[k])/(x[k + 1] - x[k]), x[k] <= y <= x[k + 1]}}];

Plot[Evaluate[aa[#][y] & /@ {0, 1, 2, 3}], {y, 0, 3}, PlotLegends -> "Expressions"]

Mathematica graphics

Alternatively, you can plot each function aa[k][y] seperately and combine using Show:

Show[j = 1; 
 Plot[Evaluate[aa[#][y]], {y, 0, 3}, PlotStyle -> ColorData[3, "ColorList"][[k++]], 
    PlotLegends -> "Expressions"] & /@ {0, 1, 2, 3}]

Mathematica graphics

$\endgroup$
2
  • $\begingroup$ Are there any general form for /@ {0, 1, 2, 3}? For example /@{Do[L;, {L, 0, n - 1}]} . $\endgroup$
    – bahram
    Commented Apr 25, 2016 at 15:14
  • $\begingroup$ #bahram, you can use Range[0,3] to get {0,1,2,3} $\endgroup$
    – kglr
    Commented Apr 25, 2016 at 15:15

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.