diff --git a/ModFile.cc b/ModFile.cc
index 6b376764f663629227539f79209b1d1021601232..06e9f19a4610ee6a192dccd4f9a6e9c8b9550fa4 100644
--- a/ModFile.cc
+++ b/ModFile.cc
@@ -575,7 +575,12 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo
     mOutputFile << "warning off" << endl; // This will be executed *after* function warning_config()
 
   if (clear_all)
-    mOutputFile << "clear all" << endl;
+    mOutputFile << "if isoctave || matlab_ver_less_than('8.6')" << endl
+                << "    clear all" << endl
+		<< "else" << endl
+		<< "    clearvars -global" << endl
+		<< "    clear_persistent_variables(fileparts(which('dynare')))" << endl
+		<< "end" << endl;
   else if (clear_global)
     mOutputFile << "clear M_ options_ oo_ estim_params_ bayestopt_ dataset_;" << endl;