I am looking for a way to create a field that is piecewise constant over the finite elements. Currently, I’m able to create by iterating over the coordinates of the degrees of freedom as:

V = FunctionSpace(mesh, "DG", 0)
C = Function(V) # field I want to create
for i,x in enumerate(V.tabulate_dof_coordinates()):
C.vector().vec().setValueLocal(i, values[i] ) # value contains the values to set at each dof

what I’m missing is a way to relate each dof coordinate with the element it belongs to. Is there a way to do this? or perhaps there is a better approach to accomplish my goal?

Hello, the field will have in general a different value at each element, so I would have to define a different material for each finite element. I think this approach would be very inefficient.

The field will assume random values at each element, so spatial coordinates are not important. I would just have a list of length equal to the number of finite elements representing the field, and when I somehow iterate over the elements I pick up a value from the list.

Since the values are random, make numpy array of length V.dim() (using for instance the random Python package). The you can do C.vector()[:]=randomarray