Search code examples
wolfram-mathematicaminimization

how to store the output of Minimization


I minimize a multivariable function in Mathematica using Minimization. It works fine. I want to pass the output of the Minimization to variables in order to use them ahead. But I am missing something. Let's see it (the Etet function is defined earlier in the code and it's ok).

J1 = 1; J2 = 1; D1 = 0.1; D2 = 0;
list1 = {θ1n, θ2n, θ3n, θ4n, ϕ1n, ϕ2n, ϕ3n, ϕ4n};
{Emin, list1} = Minimize[Etet[J1, J2, D1, D2, θ1, θ2, θ3, θ4, ϕ1, ϕ2, ϕ3, ϕ4],
   {θ1, θ2, θ3, θ4, ϕ1, ϕ2, ϕ3, ϕ4}];   

When I enter:

 list1

I get:

{θ1 -> -2.35619, θ2 -> 0.785398, θ3 -> -2.35619, θ4 -> -0.785398,
 ϕ1 -> 4.71239, ϕ2 -> 1.89763*10^-8, ϕ3 -> 1.5708, ϕ4 -> -2.75641*10^-8}

however the value -2.35619 is not actually stored in θ1 etc.

How can I change this?


Solution

  • You can use ReplaceAll (/.)

    θ1 = θ1 /. list1
    

    Or all at once

    Clear[θ1, θ2, θ3, θ4, ϕ1, ϕ2, ϕ3, ϕ4]
    
    J1 = 1; J2 = 1; D1 = 0.1; D2 = 0;
    
    {Emin, list1} = Minimize[Etet[J1, J2, D1, D2, θ1, θ2, θ3, θ4, ϕ1, ϕ2, ϕ3, ϕ4],
       {θ1, θ2, θ3, θ4, ϕ1, ϕ2, ϕ3, ϕ4}];
    
    {θ1, θ2, θ3, θ4, ϕ1, ϕ2, ϕ3, ϕ4} = {θ1, θ2, θ3, θ4, ϕ1, ϕ2, ϕ3, ϕ4} /. list1
    

    And more neatly

    Clear[θ1, θ2, θ3, θ4, ϕ1, ϕ2, ϕ3, ϕ4]
    
    J1 = 1; J2 = 1; D1 = 0.1; D2 = 0;
    
    vars = {θ1, θ2, θ3, θ4, ϕ1, ϕ2, ϕ3, ϕ4};
    
    {Emin, list1} = Minimize[Etet[J1, J2, D1, D2, θ1, θ2, θ3, θ4, ϕ1, ϕ2, ϕ3, ϕ4], vars ];
    
    With[{vars = vars}, vars = vars /. list1]
    
    θ1
    

    -2.35619

    With is required to pass the values down to the variables within vars.