Search code examples
matlaboctavesymbolic-mathnumerical-computing

How to convert a symbolic expression to a Octave function from the Symbolic Package?


How to convert a symbolic expression to a Octave function from the Symbolic Package?

After installing the symbolic package on octave with pkg install -forge symbolic. Using the symbolic package on octave I may write this:

octave> pkg load symbolic;
octave> a = sym( "a" );
octave> int ( a^2 + csc(a) )

which will result in:

ans = (sym)

   3
  a    log(cos(a) - 1)   log(cos(a) + 1)
  -- + --------------- - ---------------
  3           2                 2

But how to do this Integral (int(1)) symbolic result just above to became a valuable function like this below?

function x = f( x )

    x = x^3/3 + log( cos(x) - 1 )/2 - log( cos(x) + 1 )/2

end

f(3)

# Which evaluates to: 11.6463 +  1.5708i

I want to take the symbolic result from int ( a^2 + csc(a) ), and call result(3), to compute it at 3, i.e., return the numeric value 11.6463 + 1.5708i, from the symbolic expression integral a^2 + csc(a). Basically, how to use the symbolic expression as numerically evaluable expressions? It is the as this other question for Matlab.

References:

  1. http://octave.sourceforge.net/symbolic/index.html
  2. How do I declare a symbolic matrix in Octave?
  3. Octave symbolic expression
  4. Julia: how do I convert a symbolic expression to a function?
  5. What is symbolic computation?

Solution

  • You can use pretty.

    syms x;
    x = x^3/3 + log( cos(x) - 1 )/2 - log( cos(x) + 1 )/2;
    pretty(x)
    

    which gives this:

                                         3
    log(cos(x) - 1)   log(cos(x) + 1)   x
    --------------- - --------------- + --
           2                 2           3
    

    Update (Since the question is edited):

    Make this function:

    function x = f(y)
        syms a;
        f(a) = int ( a^2 + csc(a) );
        x = double(f(y));
    end
    

    Now when you call it using f(3), it gives:

    ans =
      11.6463 + 1.5708i