I have a numpy array defining a field on my domain where each element in the array corresponds to a grid point on my mesh. I’d like to define a GridFunction on my mesh and then import the numpy array into the grid function but I haven’t found any means of doing this. Is there an easy way to do this?

Alternatively, is there a way to determine which mesh coordinate is associated with each value in the GridFunction vector so I can manually change the values according to my numpy array?

Thanks.

Hi elizabethmonte,

I would suggest using the VoxelCoefficient function to convert numpy arrays and then interpolate it into a GridFunction (if necessary)

```
mesh = Mesh(unit_square.GenerateMesh(maxh=0.2))
nx = 5
ny = 10
values = np.array([(sin(x) + cos(y)) for y in np.linspace(0,2*np.pi,ny) for x in np.linspace(0,2*np.pi, nx)])
values = values.reshape(nx,ny)
func = VoxelCoefficient((0,0), (1,1), values, linear=True)
H = H1(mesh, order=2)
gfu = GridFunction(H)
gfu.Set(func)
Draw(func, mesh, "func")
Draw(gfu, mesh, "gfu")
```

Best,

Michael

If the values correspond to vertices in the mesh, then use a gridfunction on an H1 space of order 1.

Where does your mesh come from? Do you know the ordering of the vertices in the mesh? The GridFunction entries are ordered the same way the mesh vertices are.

You can get a numpy array view onto the memory of the GridFunction vector by calling

`u.vec.FV().NumPy()`

for example

```
fes = H1(mesh, order=1)
u = GridFunction(fes)
u.vec.FV().NumPy()[:] = values
```

you can get the coordinates of the mesh vertices from the mesh:

```
for v in mesh.vertices:
print("Vertex {} has coordinates {}".format(v.nr, v.point))
```

Best

Christopher