简体   繁体   中英

How do I rewrite equations from matlab for use in c++

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?

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

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.

您可以使用战俘家庭。

在C ++中, pow()函数对整数幂进行了重载-它对^ 2,3等使用更快的算法

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM