I have derived and simplified an equation in Matlab and want to use it in a c++ program. Matlab likes to use powers, the ^ sign but c++ doesn't like it one bit. How can i get Matlab to rewrite the equation so that it outputs a c++ friendly equation?
In C++ the pow() function is overloaded for integer powers - it uses a faster algorithm for ^2,3 etc
There is a Matlab Clone Octave which uses the same Syntax as Matlab (I don't know how much of the syntax is supported though). Since it is Open Source, maybe you can reuse the parser (I read something about it from the author in that "a bit old" thread as well).
Afterwards you can create C++ Code from the syntax tree.
And then there is also a tool for converting Matlab into C code. I havent used it yet and it is not available for free.
If the equation is really so long that you don't want to go through by hand, one option you might consider for reformatting the equation to make it C++ friendly is to parse the text of the MATLAB code for the equation using the REGEXPREP function in MATLAB. Here's an example of how you could replace expressions of the form x^2
or y.^3
with pow(x,2)
or pow(y,3)
:
eqStr = 'the text of your equation code'; %# Put your equation in a string
expr = '(\w+)\.?\^(\d+)'; %# The pattern to match
repStr = 'pow($1,$2)'; %# The replacement string
newStr = regexprep(eqStr,expr,repStr); %# The new equation string
You would just have to take the code for your MATLAB equation and put it in a string variable eqStr
first. The output from REGEXPREP will then be the text for your new C++ friendly equation newStr
.
You could also change the replacement string to give you results of the form x*x
or y*y*y
using dynamic operators. For example:
eqStr = 'the text of your equation code'; %# Put your equation in a string
expr = '(\w+)\.?\^(\d+)'; %# The pattern to match
repStr = '${repmat([$1,''*''],1,$2-''0''-1)}$1'; %# The replacement string
newStr = regexprep(eqStr,expr,repStr); %# The new equation string