[英]How do I rewrite equations from matlab for use in c++
我已经在Matlab中推导并简化了一个方程,想在c ++程序中使用它。 Matlab喜欢使用幂, ^
符号,但c ++一点也不喜欢。 如何让Matlab重写方程式,以便输出c ++友好方程式?
如果方程式的时间过长而又不想手工处理,则可以考虑重新格式化该方程式以使其对C ++友好的一种方法是使用REGEXPREP函数解析该方程式的MATLAB代码文本MATLAB。 这是如何使用pow(x,2)
或pow(y,3)
替换x^2
或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
您只需要获取MATLAB方程的代码,然后将其放在字符串变量eqStr
。 REGEXPREP的输出将成为新的C ++友好方程newStr
。
您还可以使用动态运算符更改替换字符串,以提供x*x
或y*y*y
形式的结果。 例如:
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
一种方法是使用ccode MATLAB函数,该函数将符号表达式转换为C代码。 例如ccode(sym('(x+y)^2'))
返回t0 = pow(x+y,2.0);
。 当然,不要忘记在C ++程序中using namespace std
(或仅将pow
替换为std::pow
),否则它将无法编译。 有关ccode的更多信息,请阅读MATLAB的帮助。
您可以使用战俘家庭。
在C ++中, pow()函数对整数幂进行了重载-它对^ 2,3等使用更快的算法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.