diff --git a/miscmaths.cc b/miscmaths.cc
index 80a970d08e280759b65600505d235ad699dab1d4..9def6728dd57814e684219532cb40eda52ff7711 100644
--- a/miscmaths.cc
+++ b/miscmaths.cc
@@ -2183,9 +2183,16 @@ void ols(const Matrix& data,const Matrix& des,const Matrix& tc, Matrix& cope,Mat
 }
 
 float ols_dof(const Matrix& des){
+  if ( des.Nrows() > 4000 ) //Use the simple version as huge designs require too much RAM in the full calculation
+    return des.Nrows() - des.Ncols();
+  try {
   Matrix pdes = pinv(des);
   Matrix R=IdentityMatrix(des.Nrows())-des*pdes;
-  return R.Trace();
+  return R.Trace();}
+  catch (...) {
+    cerr << "ols_dof: Error in determining the trace, resorting to basic calculation" << endl;
+  }
+  return des.Nrows() - des.Ncols();
 }
 
 int conjgrad(ColumnVector& x, const Matrix& A, const ColumnVector& b, int maxit,