1
$\begingroup$

I found a Mathematica notebook on the internet, which calculates the inverse kinematics of a 6DoF robot.
link to the notebook

In one part of the code it gives a symbolic expression using the Solve[] function.

(For easier writing "Th" means now the greek letter "theta" - the joint variable)

 sol5 = Solve[-Cos[Th5]] == nx Cos[Th1] + ny Sin[Th1], {Th5}];

Later a Compile[] function is using it, but now with the already solved full form of the equation.

theta5 = Compile[{
{Th1, _Real},
{{nx, _Real}, {ny, _Real}},
Module[{...local variables...},

(*and here is the symbolic equation*)
{-ArcCos[-nx Cos[Th1] - ny Sin[Th1]],  
 ArcCos[-nx Cos[Th1] - ny Sin[Th1]]}
]];

(The exact theoretical background of the problem is not important right now.)

My question is the following:
Is there a way to make it so, that when the equation (used in Solve) changes, this modification is also reflected automatically inside the Compile function?

Conceptually, it would be similar to storing a value in a variable and having the Compile directly use that. Of course, that’s not possible as-is, since Solve works symbolically while Compile operates numerically.

Here's the WRONG way:

sol5 = Solve[-Cos[Th5] == nx Cos[Th1] + ny Sin[Th1], {Th5}]
sol5a = Th5 /. sol5[[1]];  
sol5b = Th5 /. sol5[[2]]; 

theta5 = Compile[{
    {Th1, _Real},
    {{nx, _Real}, {ny, _Real}},
    Module[{...local variables...},
    {sol5a, sol5b} (*this part is, what I'm most interested in*)
    ]];

In this example it's a pretty short and easy expression. But in other part of the code it's much more complicated. So it would be with this way. It doesn't matter what the expression is, we store it somewhere and maybe modify it to be suitable for the Compile.

If it's impossible, or maybe I should start thinking about an other way, I'm happy to recieve that answer too.

Thanks! Gyuri

$\endgroup$
4
  • $\begingroup$ Strongly related, if not duplicate: mathematica.stackexchange.com/q/255577/1871 $\endgroup$ Commented Oct 23 at 10:31
  • $\begingroup$ Hard to answer without a specific example. Possibly have an outer Module that calls SolveValues, and inject the result into Compile. A drawback is that it would then compile anew at each call to the Module. $\endgroup$ Commented Oct 23 at 15:00
  • $\begingroup$ Also, what would happen if Solve[] fails returning nothing? Then the compiled code will also fail, possibly crashing the session? Some delicate error handling would be required I think. $\endgroup$ Commented Oct 24 at 13:15
  • $\begingroup$ If you just want to increase the speed, you can change Solve to NSolve instead of using Compile. $\endgroup$ Commented Oct 25 at 1:28

0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.