valerio_sperati
valerio_sperati

Reputation: 823

Matlab mexFunction(): when and how many times is it called?

A question about Matlab and C function (I'm not expert in Matlab):

I have a working matlab code (downloaded from internet) which calls a function 'foo':

[output] = foo(input)

Now, this function 'foo' is defined inside a 'C' file (foo.c), which was then compiled as a library for Matlab (foo.mexa64). Looking at foo.c, I can see there are two functions:

  1. void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
  2. void foo(double* out, double* in);

As I understand, the mexFunction() allocates pointers for input and outputs, and fill them with proper data from Matlab code.

My question is: if Matlab calls foo several times, is mexFunction() called everytime or it is called just the first time?

Upvotes: 0

Views: 96

Answers (2)

sebastian
sebastian

Reputation: 9696

mexFunction is called very time the MATLAB-foo is called.

That's just how the mex-interface works:

You give MATLAB a mex-file and MATLAB just calls the mexFunction out of this library, everytime you invoke the function. Basically, MATLAB doesn't care about anything else in your library.

If you'd like to call only the C-version of foo, you might want to look into the documentation of loadlibrary and the referenced function therein.

Upvotes: 1

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

It is called every time foo is called; the inputs of the MEX function are in general different, therefore, the desired outputs need to be re-computed by the MEX function.

Upvotes: 2

Related Questions