I have the following problem:

gigi[a_, b_, c_, d_, e_, f_] := With[{go = 2},
  a + b^2 + b + d^2 + e + f^2;
  dfe = 2;
  dd = Log[a] + dfe + go;
  Export["pd.dat", dd];
  alt = Import["pd.dat"]

Its only an example, as my real code is too complicate to post here. I am obliged to export and read a file (since one of my functions in a package has to read files and I can't modify it). If one runs this function with some input arguments it work good. Problems begin when I want to minimize this function.

Minimize[{gigi[a, b, c, d, e, f]}, {a, b, c, d, e, f}, 
 StepMonitor :> Print["Step to x = ", a]]

The export of the files messes up with FindMinimum. What can I do??

  • 1
    $\begingroup$ Is StepMonitor a valid option for Minimize? $\endgroup$
    – Rashid
    May 7, 2016 at 23:13
  • 1
    $\begingroup$ It looks like the problem is that you are exporting the definition of dd into the file pd.dat, but it isn't getting imported back correctly. In other words, altdd. If you want them to be identical, you could try: alt =ToExpression[Import["pd.dat", "String"]] $\endgroup$
    – Rashid
    May 7, 2016 at 23:51
  • $\begingroup$ This was what I was looking for!! $\endgroup$ May 8, 2016 at 8:53

1 Answer 1


As explained in the comments above, the problem is that Import["pd.dat"] does not correctly interpret the exported text file. You can see this by evaluating gigi[a, b, c, d, e, f] which returns {{4, "+", "Log[a]"}}. Since the file "pd.dat" contains only "4 + Log[a]", this gets interpreted as the number 4, followed by a "+" sign, followed by the string "Log[a]".

To fix this, you can use the Get[] function that reads in and evaluates each expression. For example, you could change the import line to read: alt = Get["pd.dat"]. (This is effectively identical to my comment suggestion to use alt=ToExpression[Import["pd.dat", "String"]])

If your goal is to export and import full definitions though, you may also consider using the Save[] function together with Get[]. Save creates a text file that includes the variable name. For example, Save["pd2.dat", dd] creates a file that reads "dd = 4 + Log[a]". Then if you Get["pd2.dat"] this will set dd equal to 4+Log[a].

Using Save[] and Get[] together is easier, but can also overwrite definitions. Here is an illustrative example where dd is saved, clear, then imported during Get:

gigi2[a_, b_, c_, d_, e_, f_] := 
 With[{go = 2}, a + b^2 + b + d^2 + e + f^2;
  dfe = 2;
  dd = Log[a] + dfe + go;
  Save["pd2.dat", dd];

gigi2[a, b, c, d, e, f]
 (* 4 + Log[a] *)

 (* 4 + Log[a] *)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.