core/matlab/examples/mx/mxcreatecharmatrixfromstr.c

00001 /*=================================================================
00002  * mxcreatecharmatrixfromstr.c
00003  * 
00004  * This example takes MATLAB strings as inputs.  It returns a
00005  * vertically concatenated matrix of the input strings.  If the
00006  * example is compiled as follows:
00007  *
00008  *   mex mxcreatecharmatrixfromstr.c -DSPACE_PADDING
00009  *
00010  * it will create a matrix with space padding.  If it is compiled
00011  * without the flag, the matrix of strings that is created will have
00012  * NULL padding.
00013  *
00014  * This is a MEX-file for MATLAB.  
00015  * Copyright 1984-2006 The MathWorks, Inc.
00016  * All rights reserved.
00017  *=================================================================*/
00018 
00019 /* $Revision: 1.1 $ */
00020 #include "mex.h"
00021 
00022 void
00023 mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
00024 {
00025     int i;
00026     char *str[100];
00027 
00028     /* Check for proper number of input and output arguments */    
00029     if (nrhs < 2) {
00030     mexErrMsgTxt("At least two input arguments required.");
00031     } 
00032     if(nlhs > 1){
00033     mexErrMsgTxt("Too many output arguments.");
00034     }
00035     
00036     for (i=0; i<nrhs; i++){
00037     /* Check input to be sure it is of type char. */
00038     if(!mxIsChar(prhs[i])){
00039         mexErrMsgTxt("Input must be of type char.");
00040     }
00041     /* Copy the string data from prhs and place it into str. */ 
00042         str[i] = mxArrayToString(prhs[i]); 
00043     }
00044     
00045     /* Create a 2-Dimensional string mxArray with NULL padding. */
00046     plhs[0]= mxCreateCharMatrixFromStrings((mwSize)nrhs, (const char **)str); 
00047 
00048     /* If compile with -DSPACE_PADDING, convert NULLs to spaces */
00049 #if defined(SPACE_PADDING)
00050     {
00051         mwSize j;
00052         mwSize nelem = mxGetNumberOfElements(plhs[0]);
00053         mxChar *charData = (mxChar *)mxGetData(plhs[0]);
00054     for(j=0; j < nelem; j++) {
00055         if(charData[j] == (mxChar) 0) {
00056             charData[j] = (mxChar) ' ';
00057         }
00058     }
00059     }
00060 #endif
00061     /* Free the allocated memory */
00062     for (i=0; i<nrhs; i++){
00063         mxFree(str[i]); 
00064     }
00065 }
00066 

GridLAB-DTM Version 1.0
An open-source project initiated by the US Department of Energy