Search code examples
cmatlaboctavemex

why this code is not calling Matlab function


I have written a code in MATLAB to add two numbers. The code is given below:

function [z] = addition(x,y)
    z=x+y;
end

I have written another code in C to call this addition function. The code is given below:

#include "mex.h"

void  mexFunction (int nlhs, mxArray* plhs[],
      int nrhs, const mxArray* prhs[])
{
    mxArray *a,*b,*c;
    a=mxCreateDoubleMatrix(1, 1, mxREAL);
    b=mxCreateDoubleMatrix(1, 1, mxREAL);
    a=1;
    b=1;
    mexCallMATLAB(1,&c, 2, &b, &a, "addition");
    mexCallMATLAB(0,NULL,1, &c, "disp");
    mxDestroyArray(a);
    mxDestroyArray(b);

    return;
}

please tell me why it is not working??? thanks


Solution

  • There are a couple of issues with the code:

    • The way you assign values to the mxArray's a and b is incorrect.
    • the way you pass the inputs to mexCallMATLAB is also not correct

    Here is my implementation:

    callAdd.c

    #include "mex.h"
    
    void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
    {
        mxArray *in[2], *out[1];
    
        in[0] = mxCreateDoubleScalar(5);
        in[1] = mxCreateDoubleScalar(4);
    
        mexCallMATLAB(1, out, 2, in, "addition");
        mexCallMATLAB(0, NULL, 1, out, "disp");
    
        mxDestroyArray(in[0]);
        mxDestroyArray(in[1]);
        mxDestroyArray(out[0]);
    }
    

    This is basically equivalent to calling disp(addition(5,4)) in MATLAB