# User-defined expression for tensor coefficient

**URL:** <https://fenicsproject.discourse.group/t/user-defined-expression-for-tensor-coefficient/3899>\
**Category:** variational formulation\
**Created:** [August 5, 2020, 11:12am UTC](https://fenicsproject.discourse.group/t/user-defined-expression-for-tensor-coefficient/3899 "2020-08-05T11:12:28Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [August 5, 2020, 12:04pm UTC](https://fenicsproject.discourse.group/t/user-defined-expression-for-tensor-coefficient/3899/2 "2020-08-05T12:04:51Z")

</div>

The array that is input into `eval` is a 1D array, where the first 2 entries are the first row in the tensor, the next 2 are the next row etc. I’ve made a minimal 2D example to illustrate this:

```auto

from dolfin import *
import numpy as np
mesh = UnitSquareMesh(1,1)
V = VectorFunctionSpace(mesh, "CG", 1)
unp = np.array([1,2,3,4])
u = as_tensor(unp.reshape((2,2)).tolist())

class Tensor_Coeff(UserExpression):
    def init(self, **kwargs):
        super().init(**kwargs)
    def eval(self, values, x):
        values[0] = 0
        values[1] = 1
        values[2] = 2
        values[3] = 3
        #print("LOCAL tensor\n", values.reshape(self.value_shape()))
    def value_shape(self):
        return (2,2)

expr = Tensor_Coeff()
for i in range(2):
    for j in range(2):
        print("i", i,"j", j, "assembled",
              assemble(u[i,j]*expr[i,j]*dx(domain=mesh)),
              "exact",(2*i+j)*unp[2*i+j])

```

---

_[View the full topic](https://fenicsproject.discourse.group/t/user-defined-expression-for-tensor-coefficient/3899)._
