How to convert symbolic expressions to vectorized functions in MATLAB?

爷,独闯天下 提交于 2019-12-11 10:38:18

问题


Can MatLab convert something like

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

to

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

automatically?

Example

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

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


回答1:


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

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

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

so now

>> v(3)
ans =
     6


来源:https://stackoverflow.com/questions/29408972/how-to-convert-symbolic-expressions-to-vectorized-functions-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!