1 // mex_demo.c -- example of a dynamically linked function for Octave.
2 
3 // To compile this file, type the command
4 //
5 //   mkoctfile --mex mex_demo.c
6 //
7 // from within Octave or from the shell prompt.  This will create a file
8 // called mex_demo.mex that can be loaded by Octave.  To test the mex_demo.mex
9 // file, start Octave and type the command
10 //
11 // d = mex_demo ("easy as", 1, 2, 3)
12 //
13 // at the Octave prompt.  Octave should respond by printing
14 //
15 //   Hello, world!
16 //   I have 4 inputs and 1 output
17 //   d =  1.2346
18 
19 // Additional samples of code are in the examples directory of the Octave
20 // distribution.  See also the chapter External Code Interface in the
21 // documentation.
22 
23 #include "mex.h"
24 
25 // Every user function should include "mex.h" which imports the basic set of
26 // function prototypes necessary for dynamically linked functions.  In
27 // particular, it will declare mexFunction which is used by every function
28 // which will be visible to Octave.  A mexFunction is visible in Octave under
29 // the name of the source code file without the extension.
30 
31 // The four arguments to mexFunction are:
32 // 1) The number of return arguments (# of left-hand side args).
33 // 2) An array of pointers to return arguments.
34 // 3) The number of input arguments (# of right-hand side args).
35 // 4) An array of pointers to input arguments.
36 
37 void
mexFunction(int nlhs,mxArray * plhs[],int nrhs,const mxArray * prhs[])38 mexFunction (int nlhs, mxArray *plhs[],
39              int nrhs, const mxArray *prhs[])
40 {
41   mexPrintf ("Hello, World!\n");
42 
43   mexPrintf ("I have %d inputs and %d outputs\n", nrhs, nlhs);
44 
45   /* Demonstrate returning a matrix with a double value */
46   mxArray *v = mxCreateDoubleMatrix (1, 1, mxREAL);
47   double *data = mxGetPr (v);
48   *data = 1.23456789;
49   plhs[0] = v;
50 
51   /* Return empty matrices for any other outputs */
52   int i;
53   for (i = 1; i < nlhs; i++)
54     plhs[i] = mxCreateDoubleMatrix (0, 0, mxREAL);
55 }
56