¥»¸ªº MEX ÀÉ®×¬O putarray.c¡A¥i±N¿é¤J¯x°}­¼¥H 2 ¤§«á¡A¦s©ñ¦¨ MATLAB °ò¥»¤u§@ªÅ¶¡¤¤ªº¤@­ÓÅÜ¼Æ¡A¨äµ{¦¡½X¦p¤U¡F

/*=================================================================
* putarray.c
*
* This example demonstrates how to use mexPurVariable and mexFunctionName.
* This function takes an input argument, multiplies it by two, and put
* it into MATLAB base workspace under a variable name "putarray_output".
*
* Roger Jang, 19991003, 20070223
/*=================================================================*/

#include <stdio.h>
#include <string.h>
#include <math.h>
#include "mex.h"	/* mex.h ¥]§t mxArray µ²ºcªº©w¸q¡A¥H¤Î¨ä¥L¬ÛÃö¸ê°T */

/* prhs = pointer to the right-hand-side arguments¡A§Y«ü¦V¿é¤JÅÜ¼Æ¦Cªº«ü¼Ð */
#define IN prhs[0]	/* ©w¸q IN ¬°¦¹¨ç¦¡ªº²Ä¤@­Ó¿é¤JÅÜ¼Æ¡A¥H«K«áÄò¨ú¥Î */

void
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) {
char arrayName[40];
mxArray *arrayPtr;
int i, status;

/* ÀË¬d¿é¥XÅÜ¼Æ­Ó¼Æ¬O§_¬°0¡B¿é¤JÅÜ¼Æ­Ó¼Æ¬O§_¬°1¡A¨ä¤¤      */
/* nrhs = no. of right-hand-side arguments¡]¿é¤JÅÜ¼Æ­Ó¼Æ¡^ */
/* nlhs = no. of  left-hand-side arguments¡]¿é¥XÅÜ¼Æ­Ó¼Æ¡^ */
if (nrhs!=1) { mexErrMsgTxt("One input arguments required."); }
if (nlhs>1) { mexErrMsgTxt("Too many output arguments."); }

/* ÀË¬d¿é¤JÅÜ¼Æ¸ê®Æ«¬ºA¬O§_²Å¦X­n¨D */
if (!mxIsDouble(IN) || mxIsComplex(IN))
mexErrMsgTxt("Input must be real double.");

strcpy(arrayName, mexFunctionName());
strcat(arrayName,"_output");

/* ²£¥Í¤@­Ó¸ê®Æ«¬ºA¬°doubleªº°}¦C */
arrayPtr = mxCreateDoubleMatrix(mxGetM(IN), mxGetN(IN), mxREAL);

/* ±N¦¹°}¦Cªº¹ê³¡­¼¥H2 */
for (i=0; i<mxGetM(IN)*mxGetN(IN); i++)
mxGetPr(arrayPtr)[i] = 2*(mxGetPr(IN)[i]);

/* ±N¦¹°}¦C°e¨ìMATLABªº°ò¥»¤u§@ªÅ¶¡ */
status = mexPutVariable("base", arrayName, arrayPtr);

if (status==1){	/* µLªk±N¦¹°}¦C°e¨ìMATLABªº°ò¥»¤u§@ªÅ¶¡¡A¦L¥X¥¢±Ñ°T®§ */
mexPrintf("Variable %s\n", arrayName);
mexErrMsgTxt("Could not put variable in the base workspace.\n");
}
/* ¦¨¥\¦a±N¦¹°}¦C°e¨ìMATLABªº°ò¥»¤u§@ªÅ¶¡¡A¦L¥X¦¨¥\°T®§ */
mexPrintf("\"%s\" is created in the base workspace.\n", arrayName);

/* §R°£¥ý«e²£¥Íªº°}¦C¡A±N¦û¥Îªº°O¾ÐÅéÂkÁÙµ¹§@·~¨t²Î*/
mxDestroyArray(arrayPtr);
}
`

¥i½sÄ¶¤Î´ú¸Õ¦p¤U¡G

>> clear all >> mex putarray.c >> putarray([1 2 5]) "putarray_output" is created in the base workspace. >> whos Name Size Bytes Class Attributes putarray_output 1x3 24 double ¨ä¤¤ putarray_output §Y¬O¥Ñ putarray ©Ò¸m©ñ¦b MATLAB °ò¥»¤u§@ªÅ¶¡ªºÅÜ¼Æ¡A¥i¥HÀËµø¦p¤U¡G >> putarray_output putarray_output = 2 4 10

³o­Ó MEX ÀÉ®×½d¨Ò¬Û·í­«­n¡A¥i¯àªºÀ³¥Î«Ü¦h¡A¨Ò¦p¡G

• ±q RS232 °ðÅª¨ú GPS ¶Ç¦^ªº¸ê®Æ¡A±N¸ê®Æ¶i¦æªì¨Bªº³B²z«á°e¤J MATLAB ªº°ò¥»¤u§@ªÅ¶¡¡AMATLAB ¦A®Ú¾Ú¦¹¤u§@ªÅ¶¡ªºÅÜ¼Æ¶i¦æ§Y®Éªº¹Ï§ÎÃ¸»s©Î¦¨¹³¡C