Пример #1
0
int main(int argc, char *argv[])
{
	MATFile *mat;
	const char* name = NULL;
	const mwSize* dims;

	if (argc != 2) {

		fprintf(stderr, "Usage: %s file.mat\n", argv[0]);
		exit(1);
	}


	if (NULL == (mat = matOpen(argv[1], "r")))
		exit(1);

	mxArray* ar;

	while (NULL != (ar = matGetNextVariable(mat, &name))) {

		int ndim = (int)mxGetNumberOfDimensions(ar);
		dims = mxGetDimensions(ar);

		bool cmp = mxIsComplex(ar);
		bool dbl = mxIsDouble(ar);

		printf("%s: [ ", name);

		if ((!cmp) || (!dbl)) {

			printf("not complex double\n");
			mxDestroyArray(ar);
			continue;
		}

		long ldims[ndim];
	        for (int i = 0; i < ndim; i++)
			ldims[i] = dims[i];	

		for (int i = 0; i < ndim; i++)
			printf("%ld ", ldims[i]);

		char outname[256];
		snprintf(outname, 256, "%s_%s", strtok(argv[1], "."), name);

		complex float* buf = create_cfl(outname, ndim, ldims);
		double* re = mxGetPr(ar);
		double* im = mxGetPi(ar);

		size_t size = md_calc_size(ndim, ldims);

		for (unsigned long i = 0; i < size; i++) 
			buf[i] = re[i] + 1.i * im[i];

		printf("] -> %s\n", outname);

		unmap_cfl(ndim, ldims, buf);
		mxDestroyArray(ar);
	}

	matClose(mat);
}
Пример #2
0
  bool mat_load_multi_array_vec2(MATFile *f, QString qsVarName, std::vector<std::vector<Array> > &vvA)
  {
    const char *name = 0;
    bool bRes = false;
    vvA.clear();

    if (f != 0) {
      mxArray *matlab_mat = matGetNextVariable(f, &name);
      std::cout << name << std::endl;

      bool bLoaded = false;

      while (matlab_mat != 0 && !bLoaded) {
        if (qsVarName == name) {
          if (mxIsCell(matlab_mat)) {
            mwSize cell_ndim = mxGetNumberOfDimensions(matlab_mat);
            const mwSize *cell_dims = mxGetDimensions(matlab_mat);
            //std::cout << "number of cell dimensions: " << cell_ndim << endl;

            assert(cell_ndim == 2);
            for (int dim_idx = 0; dim_idx < 2; ++dim_idx) {
              std::cout << "extent of cell dim " << dim_idx << ": " << cell_dims[dim_idx] << std::endl;
            }            

            uint N1 = cell_dims[0];
            uint N2 = cell_dims[1];            
            
            //vvA.resize(N1, std::vector<Array>(N2, Array()));

            for (uint i1 = 0; i1 < N1; ++i1) {
              vvA.push_back(std::vector<Array>());
              for (uint i2 = 0; i2 < N2; ++i2) {

                /* get dimensions of the current cell */
                mwIndex subs[2];
                subs[0] = i1;
                subs[1] = i2;
                mwIndex cell_idx = mxCalcSingleSubscript(matlab_mat, cell_ndim, subs);
                mxArray *E = mxGetCell(matlab_mat, cell_idx);

                mwSize mat_ndim = mxGetNumberOfDimensions(E);
                const mwSize *mat_dims = mxGetDimensions(E);
                //std::cout << "number of cell element dimensions: " << mat_ndim << endl;
                assert(mat_ndim == Array::dimensionality);

                /* copy from matlab matrix to Array */
                boost::array<typename Array::size_type, Array::dimensionality> array_shape;
                for (uint i = 0; i < Array::dimensionality; ++i) 
                  array_shape[i] = mat_dims[i];

                Array B(array_shape, boost::fortran_storage_order());  
                uint nElements = B.num_elements();

                if (nElements > 0) {
                  typename Array::element *data2 = B.data();
                  if (mxIsSingle(E)) {
                    float *pE = (float *)mxGetPr(E);
                    assert(pE != 0);
                    for (uint i = 0; i < nElements; ++i) {
                      *(data2 + i) = *pE;
                      ++pE;
                    }
                  }
                  else {
                    double *pE = mxGetPr(E);
                    assert(pE != 0);
                    for (uint i = 0; i < nElements; ++i) {
                      *(data2 + i) = *pE;
                      ++pE;
                    }
                  }

                  //vvA[i1][i2] = B;

                  /* copy to array with normal storage order */
                  // Array A = B; // this does not work!!! (storage order is of course copied at construction :)
                  Array A(array_shape);
                  A = B;
                  
                  vvA.back().push_back(A);
                }

              }
            }// cell elements

            bRes = true;
          }// is cell
          else {
            std::cout << "variable is not a cell array" << std::endl;
          }

          bLoaded = true;
        }

        mxDestroyArray(matlab_mat);
        matlab_mat = 0;

        if (!bLoaded)
          matlab_mat = matGetNextVariable(f, &name);

      }// variables
    }

    assert(bRes && "variable not found or could not open file");
    return bRes;
  }
Пример #3
0
//----------------------
MATFile* matOpen(const char*fname,const char* read_write_fg) {
    MATFile* ret;
    //char header_str[128];
    long file_len,cur_pos;
    int ndx;
    short int endian,version;
    mxArray*tmp_var=NULL;
    time_t t;
    //-----
    //fprintf(stderr,"matOpen(%s,%s)\n",fname,read_write_fg);
    //-----
    ret=(MATFile*)calloc(1,sizeof(MATFile));
    ret->fname = fname;
    if(strcmp(read_write_fg,"r")==0) {
        ret->fd = open(fname,O_RDONLY);
        if(ret->fd<0) {
            fprintf(stderr,"Can not open file '%s' : %s\n",fname,strerror(errno));
            return NULL;
        }
        // check that we are using v5.0 MAT files ( -v6 & -v7 )
        if( read(ret->fd,&ret->header_str,128*sizeof(char)) != 128) {
            fprintf(stderr,"ERROR: short read on header\n");
            exit(0);
        }
        if( strncmp( ret->header_str , "MATLAB 5.0 MAT-file" , 19 )!=0) {
            fprintf(stderr,"ERROR: can not read this version of MAT file, use '-v6' or '-v7' with save() command\n\n");
            exit(0);
        }
        return ret;
        //-----------------
    } else if(strcmp(read_write_fg,"w")==0) {
        ret->open_for_writing=1;
        // check if the file exists
        ret->fd = open(fname,O_RDONLY);
        if(ret->fd<0) { // it does not
            memset(ret->header_str,' ',128);
            t = time(NULL);
            ndx=snprintf(ret->header_str,116,"MATLAB 5.0 MAT-file, Platform: %s, Created By: URDME-libmat v%s on %s", SYSTEM_PLATFORM, URDME_VERSION_STRING,ctime(&t));
            //ret->header_str[115] = '\0';
            ret->header_str[ndx] = ' ';
            endian = 0x4d49;
            version = 0x0100;
            memcpy(&ret->header_str[124],&version,2);
            memcpy(&ret->header_str[126],&endian,2);
            //ret->header_str, "MATLAB 5.0 MAT-file, Platform: URDME_LIBMAT Created on: TODO                                                                  IM");
            //if(strlen(ret->header_str) != 128){ fprintf(stderr,"header string is not strlen() of 128!, strlen=%lu\n",strlen(ret->header_str));exit(0); }
            return ret;
        } else { // it does
            if( read(ret->fd,&ret->header_str,128*sizeof(char)) != 128) {
                fprintf(stderr,"ERROR: short read on header\n");
                exit(0);
            }
            // read all the variables and store them in the MATFile struct
            file_len  = (long) lseek(ret->fd,0,SEEK_END);
            lseek(ret->fd, 128, SEEK_SET);
            do {
                cur_pos =  (long) lseek(ret->fd,0,SEEK_CUR);
                if(cur_pos>=file_len) {
                    break;
                }
                tmp_var = matGetNextVariable(ret);
                matPutVariable(ret, tmp_var->name, tmp_var );
            } while(tmp_var!=NULL);
            ret->has_changed=0;
            return ret;
        }
    } else {
        fprintf(stderr,"matOpen: flag is not 'r' or 'w'\n");
        exit(0);
    }
}
Пример #4
0
void
mexFunction( int nlhs, mxArray *plhs[],
	     int nrhs, const mxArray *prhs[] )
{
  MATFile *ph;

  char *matfile;
  char *varnamelist[100];
  
  int   counter=0;

  (void) nlhs;      /* unused parameters */
  (void) plhs;
  
  if(nrhs==0) {
    /*
     * no arguments; so load by default from 'matlab.mat'
     */
    matfile=(char *)mxCalloc(11,sizeof(char));
    matfile=strcat(matfile,"matlab.mat");
  }
  else {
    /* 
     * parse the argument list for the
     * filename and any variable names 
     *
     * note: the first argument must be a filename.
     *       therefore you can't request specific
     *       variables from 'matlab.mat' without
     *       passing the filename in
     */
    
    /*
     * we're adding 5 to the size of the string.
     * 1 for '\0' and 4 in case the '.mat' was
     * forgotten
     */
    mwSize buflen=mxGetN(prhs[0])+5;
    int index;
    
    /* filename */
    matfile=(char *)mxCalloc(buflen,sizeof(char));
    mxGetString(prhs[0],matfile,buflen);
    
    /* 
     * make sure '.mat' suffix exists
     */
    {
        const char *lastdot = strrchr( matfile, '.' );
        const char *lastslash = strrchr( matfile, '/' );
        const char *lastbslash = strrchr( lastslash ? lastslash : matfile, '\\');
        lastslash = lastbslash ? lastbslash : lastslash;
 
        if(!lastdot || (!lastslash || lastdot < lastslash))
            matfile=strcat(matfile,".mat");
    }

    /* variable name list */
    for(index=1;index<nrhs;index++) {
      
      mwSize varlength=mxGetN(prhs[index])+1;
      
      varnamelist[counter]=(char *)mxCalloc(varlength,sizeof(char));
      mxGetString(prhs[index],varnamelist[counter],varlength);
      
      counter++;
    }
  }

  /* open the MAT-File to read from */
  ph=matOpen(matfile,"r");

  if(ph<(MATFile *)3) {
    char errmsg[]="Failed to open '";
    
    strcat(errmsg,matfile);
    strcat(errmsg,"'");

    mxFree(matfile);
    mexErrMsgTxt(errmsg);
  }
  
  if(counter>0) {
    /* there where variables in the argument list */
    mxArray *var;
    int      index;
    
    for(index=0;index<counter;index++) {
      var=matGetVariable(ph,varnamelist[index]);
      mexPutVariable("caller", varnamelist[index],var);
      
      mxFree(varnamelist[index]);
    }
  }
  else {
    /* 
     * the variable argument list 
     * was empty so get everything 
     */
    mxArray *var;
    const char *var_name;
    
    while((var=matGetNextVariable(ph, &var_name))!=NULL) {
      mexPutVariable("caller", var_name, var);
    }
  }
  
  matClose(ph);
  mxFree(matfile);
}