Call PETSc matrix operator MatDiagonalSet (…)

It seems I always have to do the following code together (inside the time loop) in order to compute the interpolation matrix P (mesh Ths is moving but Th is static)

createMat(Th, A, PV1)|
createMat(Ths, B, PV1)|
transferMat(Th, PV1, A, Ths, PV1, B, P)
A = fluid(Rh, Rh);
B = solid(Rhs,Rhs)

One problem is I quickly ran out of memory because of (I guess) calling createMat() again and again.

Another problem is matrix A is static, It’s better to put it outside the time loop. However, when I do this, it shows the following error:

Can I somehow only put the following two lines inside the time loop, and all the other three lines outside the time loop because only Ths and matrix B change as the time involves ?

transferMat(Th, PV1, A, Ths, PV1, B, P)
B = solid(Rhs,Rhs)