MATLAB: ​How to deal with sym data type in C mex file

Symbolic Math Toolbox

I want to create a symbolic representation of an existing C code using matlab Symbolic Math toolbox.
I want mexFunction to take variables of type sym and operate some computations on it
and then print out the final result as a symbolic representation.
Is there any function that can handle sym data type in matrix APIs or mex APIs?
how can I print a sym variable from the mexfunction to the command window?

Best Answer

Operating on "syms" requires going through the MATLAB code provided with the Symbolic Math Toolbox,
whether from MATLAB or MEX files.
Within MEX files, this can be done by calling mexCallMATLAB.
Below is a small example that we hope will be able to convey you the idea.
Please refer to the MEX API for memory management and other details regarding the implementation.
    //=====================================================================
    // mexCallSym.c
    //
    // example for illustrating how to use mexCallMATLAB
    //
    // This file creates a symbolic variable x, creates the symbolic
    // expression ellipticE(x) and then integrates it with respect to x.
    // The result is returned.
    //
    // This is a MEX-file for MATLAB.
    // Copyright 2016 The MathWorks, Inc.
    //===================================================================*/
    #include "mex.h"
    //gateway function//
    void mexFunction(
            int nlhs,
            mxArray* plhs[],
            int nrhs,
            const mxArray* prhs[]){
        mxArray* xstr[1];
        mxArray* x[1];
        mxArray* f_x[1];
        mxArray* int_args[2];
        if (nlhs > 1) {
        mexErrMsgIdAndTxt("MATLAB:maxlhs", "Too many outputs");
        }
        if (nlhs < 1) {
        mexErrMsgIdAndTxt("MATLAB:minlhs", "Too few outputs");
        }
        // Remark: we may want to also ensure we didn't get parameters.
        // (Ignoring here for brevity.)
        (void) nrhs; //unused//
        (void) prhs; //unused//
        // create symbolic variable x
        xstr[0] = mxCreateString("x");
        mexCallMATLAB(1, x, 1, xstr, "sym");
        mxDestroyArray(xstr[0]);
        // create symbolic expression ellipticE(x)
        mexCallMATLAB(1, f_x, 1, x, "ellipticE");
        // integrate f_x with respect to x
        int_args[0] = f_x[0];
        int_args[1] = x[0];
        mexCallMATLAB(1, plhs, 2, int_args, "int");
        // cleanup allocated memory
        mxDestroyArray(x[0]);
        mxDestroyArray(f_x[0]);
        // Note: int_args does not point to additional allocations
        // and should not be freed
    }
In order to verify, please save the above function in the current directory and verify with the following:
    >> mex mexCallSym.c
    >> t = mexCallSym
    t =
    (2*ellipticE(x))/3 - (2*ellipticK(x))/3 + x*((2*ellipticE(x))/3 + (2*ellipticK(x))/3)