diff --git a/DynamicModel.cc b/DynamicModel.cc
index b2b5c8f67ac20f804d71961d519f2c0d7716e426..8d92a5642cf944d8010e43a263b3a947c7059b52 100644
--- a/DynamicModel.cc
+++ b/DynamicModel.cc
@@ -2508,6 +2508,7 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia
 
       DynamicOutput << "#=" << endl << comments.str() << "=#" << endl
                     << "  @assert size(g2) == (" << nrows << ", " << hessianColsNbr << ")" << endl
+                    << "  fill!(g2, 0.0)" << endl
                     << "  dynamic!(y, x, params, steady_state, it_, residual, g1)" << endl;
       if (second_derivatives.size())
         DynamicOutput << model_local_vars_output.str()
@@ -2531,6 +2532,7 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia
 
       DynamicOutput << "#=" << endl << comments.str() << "=#" << endl
                     << "  @assert size(g3) == (" << nrows << ", " << ncols << ")" << endl
+                    << "  fill!(g3, 0.0)" << endl
                     << "  dynamic!(y, x, params, steady_state, it_, residual, g1, g2)" << endl;
       if (third_derivatives.size())
         DynamicOutput << model_local_vars_output.str()
diff --git a/StaticModel.cc b/StaticModel.cc
index 8d6ba2449ad82a12c4355cceefba8cdb4d0e7ce5..ea6ed05e19bf67a078e3cb9cd48f40b538cad9eb 100644
--- a/StaticModel.cc
+++ b/StaticModel.cc
@@ -1555,6 +1555,7 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c
 
       StaticOutput << "#=" << endl << comments.str() << "=#" << endl
                    << "  @assert size(g2) == (" << equations.size() << ", " << g2ncols << ")" << endl
+                   << "  fill!(g2, 0.0)" << endl
                    << "  static!(y, x, params, residual, g1)" << endl;
       if (second_derivatives.size())
         StaticOutput << model_local_vars_output.str()
@@ -1578,6 +1579,7 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c
 
       StaticOutput << "#=" << endl << comments.str() << "=#" << endl
                    << "  @assert size(g3) == (" << nrows << ", " << ncols << ")" << endl
+                   << "  fill!(g3, 0.0)" << endl
                    << "  static!(y, x, params, residual, g1, g2)" << endl;
       if (third_derivatives.size())
         StaticOutput << model_local_vars_output.str()