2
$\begingroup$

I have the following code

SetDirectory["C:\\test"];
fname = FileNameJoin[{%, "results.dat"}];
str = OpenWrite[fname, FormatType -> StandardForm]

D1 = 0.4;
D2start = 0.26; D2fin = 0.5; Ntot = 12;
D2step = (D2fin - D2start)/Ntot;

For[i = 0, i <= Ntot, i++,
  D2 = D2start + i*D2step ;
  With[{minsol = NMinimize[fnew[D1, D2, x], x]},
  fmin = First@minsol;
  xn = Values@ Last@ minsol;];
  Write[str, D2, " ", xn]; ]
  Close[str];

i.e I minimize the function fnew with respect to x and write the value of x in the file results.dat. The problem is that the output is

0.26 {0.711259}
0.28 {0.744881}
0.3 {0.776204}
0.32 {0.805418}
...

How do I get rid of these annoying curly brackets?

$\endgroup$
2
  • $\begingroup$ What is the definition for fnew? Your likely problem is that Minimize returns a result that has two levels (e.g., {{someAnswer}}). If you set xn = Values[minsol[[1,1]]]; you might get what you want. $\endgroup$
    – Mark R
    Aug 16 '20 at 21:27
  • $\begingroup$ @Mark R No, it doesn't work. fnew is not the problem. In any case: fnew[D1_, D2_, x_] := -2 Sqrt[2] D1 Cos[x/2] - D2 Sin[x] $\endgroup$
    – geom
    Aug 16 '20 at 21:38
2
$\begingroup$

Something like this might work for you:

fnew[D1_, D2_, x_] := -2 Sqrt[2] D1 Cos[x/2] - D2 Sin[x];
fnewSolution[D1_, i_] := Block[{D2 = D2start + i*D2step, minsol, theX},
   minsol = NMinimize[fnew[D1, D2, x], x];
   theX = Values[Last[minsol]][[1]];
   {D2, theX}
   ];
D1 = 0.4;
D2start = 0.26;
D2fin = 0.5;
Ntot = 12;
D2step = (D2fin - D2start)/Ntot;
someValues = Table[fnewSolution[D1, i], {i, 0, Ntot, 1}];
Export["test.csv", someValues]

You could simply use what I wrote for "theX" to get the value without the braces. The way you output to the file is fine and you might want to consider the default methods for outputting in some interesting formats. I chose "csv" but "tsv" (tab separated value) would also work as would plain text as you were doing.

$\endgroup$
6
  • $\begingroup$ Yes, that works. Thanks! $\endgroup$
    – geom
    Aug 16 '20 at 22:22
  • $\begingroup$ Glad it works for you. $\endgroup$
    – Mark R
    Aug 16 '20 at 22:23
  • $\begingroup$ You must write your code in a way that you can use Table. Otherwise there is no way to get rid of the curly brackets. Really frustrating. Thanks again $\endgroup$
    – geom
    Aug 16 '20 at 22:25
  • 1
    $\begingroup$ Actually, using your code and changing the one line to this: xn = First@Values@Last@minsol; gives you what you want. So you don't have to use Table but it is certainly more readily used in Mathematica code than a For loop. $\endgroup$
    – Mark R
    Aug 16 '20 at 22:29
  • $\begingroup$ I meant more commonly used (not more readily used). $\endgroup$
    – Mark R
    Aug 16 '20 at 22:35

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