如何在MATLAB中将符号表达式转换为矢量化函数? [英] How to convert symbolic expressions to vectorized functions in MATLAB?

查看:448
本文介绍了如何在MATLAB中将符号表达式转换为矢量化函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MatLab可以转换类似的东西

Can MatLab convert something like

syms t real
2*t^2+5*t+6

2.*t.^2+5.*t+6

自动吗?

示例

syms t real
a=2;
v=int(a,t);

现在v=2*t,所以我想将其转换为v=2.*t.

Now v=2*t so I want to convert it to v=2.*t.

推荐答案

如果您有字符串,则可以使用

If you have a string, you can do the replacing with regexprep:

>> str = '2*t^2+5*t+6-3/t'
str =
2*t^2+5*t+6-3/t

>> str = regexprep(str, '([\*\^\/])', '.$1')
str =
2.*t.^2+5.*t+6-3./t

如您所见,这会将*^/的所有出现都更改为它们的虚线版本.

As you see, this changes all occurrences of *, ^ or / to their dotted versions.

如果字符串可能已经包含一些点分运算符,请按如下所示修改正则表达式,以避免出现双点:

If the string may already contain some dotted operators, modify the regular expression as follows to avoid double dots:

>> str = '2.*t^2+5*t+6-3./t'
str =
2*t^2+5*t+6-3/t

>> str = regexprep(str, '(?<!\.)([\*\^\/])', '.$1')
str =
2.*t.^2+5.*t+6-3./t

或者按照@knedlsepp的建议,使用 vectorize 功能:

Or, as suggested by @knedlsepp, use the vectorize function:

>> str = '2.*t^2+5*t+6-3./t'
str =
2.*t^2+5*t+6-3./t

>> str = vectorize(str)
str =
2.*t.^2+5.*t+6-3./t


如果您具有符号功能,请使用 matlabFunction 生成匿名函数:


If you have a symbolic function, use matlabFunction to generate an anonymous function:

>> syms t real
>> a=2;
>> v=int(a,t)
v =
2*t
>> v = matlabFunction(v)
v = 
    @(t)t.*2.0

所以现在

>> v(3)
ans =
     6

这篇关于如何在MATLAB中将符号表达式转换为矢量化函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆