I’m not sure if this has been answered before, and probably seems like a trivial question, but suppose that I have the following code

varf a(u,v) = int2d(Th)(dx(u)*dx(v) + dy(u)*dy(v));
matrix K = a(Vh,Vh);

and that I would like to invert the matrix K. I’ve tried inv(K) from fflapack and K^-1 and both did not work. I also skimmed through the documentation but with no luck. How do I invert a matrix object in general?

Thank you for the message and sorry for the late reply. I’m doing a time dependent simulation where I need the inverse of K at each iteration. So instead of solving K^-1*u at each step, I thought I’d just compute Kinv=K^-1 and then do Kinv*u directly to speed things up.

Also, how do you convert to a dense matrix? I tried the following incredibly slow solution

int col = K.n;
int row = K.m;
real[int,int] Kin(row,col);
for(int i=0; i<col; i++){
for(int j=0; j<row; j++){
Kin(j,i)=K(j,i);
}
}
inv(Kin);

Not sure why copying takes thing long for a 4096\times 4096 matrix!

Computing Kinv and then Kinv*u is in no way faster than computing K^-1*u. The L and U factors of the decomposition of K are computed only once, and then it’s just successive forward and backward solves, which are basically as fast as matrix-vector products.
Doing for loop in FreeFEM is slow, you should replace your loop by simply doing Kin = K;.

You understand correctly, but it’s not specific to FreeFEM, it’s almost all sparse exact factorization solvers that behave like this (SuiteSparse, MUMPS, PARDISO…).

It does not fail with a real[int, int], which is the type you used in your original snippet.