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

A function plus a function

0 votes

Hi, everybody. I use the c++ interface, and want to ask a simple question:
The solution is the summation of two finite element solutions u, w. How can I add u and w together? The straightforward formula U_sum= u+w does not work.
Thanks in advance.

asked Aug 10, 2015 by Guodong Zhang FEniCS Novice (420 points)
edited Aug 10, 2015 by Guodong Zhang

Could you specify, whether you are using python orC++ as well as the code you are using and any warnings/errormessages that your program creates? Also, maybe this could help you http://fenicsproject.org/qa/430/how-to-sum-functions

1 Answer

+2 votes

Yes, this is possible, u + w creates a new Expression which can be used in a variational problem.

However, if you want to have it as a Function, then you need to project it to a finite element space:

v = project(u + w, V)

If you know the two Functions are in the same space, you could also directly sum the degrees of freedom:

v = Function(V)
v.vector()[:] = u.vector()[:]
v.vector() += w.vector()

(Example code is untested Python but should work with minor modifications in C++.)

answered Aug 11, 2015 by logg FEniCS Expert (11,790 points)

Hi Logg

The code :

v = Function(V)
v.vector()[:] = u.vector()[:]
v.vector() += w.vector()

does not work for c++ interface. But, I found a way to cope with it:

Function U_sum(V);
*U_sum.vector()+=*u.vector();
*U_sum.vector()+=*v.vector();

Thank you very much!

...