Reputation: 13
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?
Upvotes: 1
Views: 1580
Reputation: 761
An approach would be to use the ccode MATLAB function, which converts symbolic expressions to C code. For example ccode(sym('(x+y)^2'))
returns t0 = pow(x+y,2.0);
. Of course do not forget the using namespace std
in your C++ program (or just replace pow
with std::pow
) or it won't compile. For more about ccode you can read the MATLAB's help.
Upvotes: 1
Reputation: 125874
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
Upvotes: 2
Reputation: 1303
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.
Upvotes: 0
Reputation: 96157
In C++ the pow() function is overloaded for integer powers - it uses a faster algorithm for ^2,3 etc
Upvotes: 1