I am calculating gradient of the following expression whose grad is (2x,2y) but I am getting a vector of ones as shown below. I know this is very basic but I am confused what is wrong, I am also confused about dim of x component of grad calculated on 1 by 1 grid. After calculating gradient I want to access both x and y components of the gradient. Here is the minimal example

# define mesh and function space
msh = create_unit_square(MPI.COMM_WORLD,1,1)
V = functionspace(msh, ("Lagrange", 1))
x = SpatialCoordinate(msh)
u = Function(V)
u.interpolate(lambda x: x[0]**2 + x[1]**2)
gdim = msh.geometry.dim
dg = dolfinx.fem.functionspace(msh,('DG',0,(gdim,)))
grad_int = dolfinx.fem.Function(dg)
grad_uh = dolfinx.fem.Expression(grad(u),dg.element.interpolation_points())
grad_int.interpolate(grad_uh)
grad_int.x.array

Consider that the spaces you’re employing are not rich enough to appropriately represent your exact functions on such a coarse mesh. See the following adjustment to your code such that you can compare your approximate gradient with the exact gradient.

In this example I’ve filled out the spaces such that each function is exactly represented; however, you can play with these spaces to see the implications of inexact representation of functions.

Thanks for your reply, I see. In addition, I want to access both x, y components of grad as an array I see grad_uh.x.array gives x component how to get y component as well.