3-6 ???本工?空?變數??MEX 檔?範?

` MEX ɮ׬O putarray.cAiNJx}H 2 As MATLAB 򥻤u@Ŷ@ܼơA{XpUF

lɡ]03-ε{/putarray.c^G]ǦϰUYi^
/*=================================================================
 * 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 cwqAHΨLT */

/* prhs = pointer to the right-hand-side argumentsAYVJܼƦC */
#define IN prhs[0]	/* wq IN 禡Ĥ@ӿJܼơAHK */

/* 禡M MATLAB qDn禡 */
void
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { 
	char arrayName[40];
	mxArray *arrayPtr;
	int i, status;
    
	/* ˬdXܼƭӼƬO_0BJܼƭӼƬO_1A䤤      */
	/* 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."); }

	/* ˬdJܼƸƫAO_ŦXnD */
	if (!mxIsDouble(IN) || mxIsComplex(IN))
		mexErrMsgTxt("Input must be real double.");
    
	/* MATLAB򥻤u@ŶܼƦW١AMEXDɦW[Wu_outputv */
	strcpy(arrayName, mexFunctionName());
	strcat(arrayName,"_output");

	/* ͤ@ӸƫAdouble}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}CeMATLAB򥻤u@Ŷ */
	status = mexPutVariable("base", arrayName, arrayPtr);
    
	if (status==1){	/* LkN}CeMATLAB򥻤u@ŶALXѰT */
		mexPrintf("Variable %s\n", arrayName);
		mexErrMsgTxt("Could not put variable in the base workspace.\n");
	}
	/* \aN}CeMATLAB򥻤u@ŶALX\T */
	mexPrintf("\"%s\" is created in the base workspace.\n", arrayName);
    
	/* Reͪ}CANΪOkٵ@~t*/
	mxDestroyArray(arrayPtr);
}

isĶδզpUG

>> 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 YO putarray Ҹmb MATLAB 򥻤u@ŶܼơAiH˵pUG >> putarray_output putarray_output = 2 4 10

o MEX ɮ׽dҬ۷nAi઺ΫܦhAҦpG


MATLAB{]pGig