Search code examples
matlabsymbolic-math

How to convert symbolic expressions to vectorized functions in MATLAB?


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.


Solution

  • 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