ERROR: loop variable of FOREACH must be a known variable or list of variables
Without seeing complete code, or a cut-down test case, it's hard to be sure but the error strongly suggests that:

FOREACH _mat
        ^^^^
        this variable is undeclared