This error should indicate that, for some reason, the data.frames() do not have matching dimensions. I'm kind of surprised that the stop condition didn't trigger, though. First guess would have been that the column names in mat2 do not correspond to those in mat1 after calling gsub. Could you perhaps provide the output of dim() for both data.frames()?
This might be why it doesn't work. My regex expression does not account for this. The easiest solution would be
colnames(mat1) <- gsub("_.*", "", colnames(mat1))
colnames(mat2) <- gsub("_.*", "", colnames(mat2))
This will turn ABxxxxxx_A into ABxxxxxx and ABxxxxxx_A_xxxx into ABxxxxxx. If you absolutely need to preserve the _A, you'll have to replace the pattern "_.*" in the gsub call with one that only matches the characters after and including the second underscore.
Edit: Note that this won't work if the ABxxxxxx part of the column names occurs more than once in a matrix.