# Help with implemented Piecewise in Module

Suppose we have an ODE in the form:

 f''[r] + f'[r] == t f[r]+h[r]


where

h[r_]: Piecewise[{{t, 0 <= r <= a}, {0, a < r <= 1}}]


I am using Module function and I do not know how to implement Piecewise with Module[{x,y,…},expr]. Here is my tried gcd[t0_] := Module[{t = t0},{f''[r] + f'[r]) == t f[r] + h[r]]. However, Mathematica does not know what is h[r]since h[r] defines outside the Module. Help?

• Parameter ϵ isn't defined! – Ulrich Neumann Feb 11 at 16:04

It is not clear what you are trying to do, since your question has incomplete information. You did not even show how you want to call the function.

But it is best to pass all information between functions via arguments and not use global context to read. This makes your code more robust.

ClearAll[ode, h, f, r];
ode[t_, a_] := f''[r] + f'[r] == t f[r] + h[t, a];
h[t_, a_] := Piecewise[{{t, 0 <= r <= a}, {0, a < r <= 1}}];


Now define the function

gcd[t_, ode_, f_, r_] := Module[{a = 0.5},
DSolve[ode[t, a], f[r], r]
]


Now call it

t = 0.4;
gcd[t, ode, f, r] There are other ways to do this. It will help if you showed actual example of call also.

You have few errors in your code posted. Try this

ClearAll[f, r];
h[t_, a_, r_] := Piecewise[{{t, 0 <= r <= a}, {0, a < r <= 1}}]
gcd[t_, f_, r_] := Module[{a = 0.5},
DSolve[f''[r] + f'[r] == t f[r] + h[t, a, r], f[r], r]
];
Table[gcd[t, f, r], {t, {4.2, 4.5, 0.1}}]


Gives • Nassaer here What I did: First I defined : h[t_, a_,r_] := Piecewise[{{t, 0 <= r <= a}, {0, a < r <= 1}}] and then gcd[t_,h_,r_] := Module[{a = 0.5,t=t0}, DSolve[f''[r] + f'[r] == t f[r] + h[t, a,r], f[r], r] ]; Now call it Table[gcd[t_,f_,r_] , {t, 4.2, 4.5, 0.1}] – user69676 Feb 12 at 22:11
• @user69676 one obvious problem, is that you are passing t as argument to gcd and also defining local t inside the same module. You can't do this. You have other problems. Will post corrected version – Nasser Feb 12 at 22:27
• .@Nasser Thanks! Do you how to use WhenEvent[0 <= r <= a, t], WhenEvent[ a < r <= 1,] instead of Piecewise? – user69676 Feb 13 at 0:22
• @user69676 WhenEvent is not really meant to be used in place of Piecewise. WhenEvent is for use in something completely different. With NDSolve and such. So you can just stick to Piecewise for defining functions. – Nasser Feb 13 at 0:38