# How can I get rid of curly brackets writing minimization output to file [closed]

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?

• 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. Aug 16 '20 at 21:27
• @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]
– geom
Aug 16 '20 at 21:38

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.

• Yes, that works. Thanks!
– geom
Aug 16 '20 at 22:22
• Glad it works for you. Aug 16 '20 at 22:23
• 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
– geom
Aug 16 '20 at 22:25
• 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. Aug 16 '20 at 22:29
• I meant more commonly used (not more readily used). Aug 16 '20 at 22:35