This is a read only copy of the old FEniCS QA forum. Please visit the new QA forum to ask questions

piecewise defintion of function

0 votes

Suppose I have two functions f and g defined on a mesh, such as in the following code fragment.

mesh = UnitSquareMesh(20, 20)
V = FunctionSpace(mesh, 'Lagrange', 1)

f = interpolate(Expression('x[0]+x[1]'), V)
g = interpolate(Expression('x[0]*x[1]'), V)

How can I define a function on the mesh that takes the values of f on the subdomain [0,0.5]x[0,1] and the values of g on the rest of the domain? I want to be able to do this without returning to the original expressions used to define f and g, but to only use f and g directly.

asked Feb 27, 2015 by bseguin FEniCS Novice (650 points)

1 Answer

+1 vote
 
Best answer
 h = interpolate(Expression('(x[0] <= 0.5 && x[1] <= 1.0) ? f : g', f=f, g=g), V)

Sorry, mixed up the subdomain in the initial answer, however just modify the domain as you want. If you don't understand the syntax in the expression, it is just a ternary operator in C.

answered Feb 27, 2015 by cevito FEniCS User (5,550 points)
selected Mar 2, 2015 by bseguin

Thank you for the quick response, but a plot of the function h you defined shows that it isn't what I'm looking for. Perhaps there is a typo in the code you provided?

Thanks for correcting it and mentioning what kind of syntax it is. I was able to figure out how to generalize it to include several definitions in the definition of h.

How to define a piecewise function on more pieces of the domain?
...