void MatlabWriter::write(const PointViewPtr view) { point_count_t nPoints = view->size(); auto nDimensions = m_dimTypes.size(); std::stringstream dimensionsString; for (size_t i = 0; i < nDimensions; ++i) { if (i > 0) dimensionsString << ","; dimensionsString << Dimension::name(m_dimTypes[i].m_id); } mxArray * dimensionNames = mxCreateString(dimensionsString.str().c_str()); if (!dimensionNames) { std::stringstream ss; ss << "Could not create string '" << dimensionsString.str() << "'"; throw pdal_error(ss.str()); } int result = matPutVariable(m_matfile, "Dimensions", dimensionNames); if (result != 0) { std::stringstream ss; ss << "Could not write dimension names to file: " << m_filename; throw pdal_error(ss.str()); } mxArray * points = mxCreateDoubleMatrix(nPoints, nDimensions, mxREAL); if (!points) { std::stringstream ss; ss << "Could not create a points array with dimensions " << nPoints << "x" << nDimensions; throw pdal_error(ss.str()); } double * pointsPtr = mxGetPr(points); // Matlab is column-major for (size_t j = 0; j < nDimensions; ++j) { for (point_count_t i = 0; i < nPoints; ++i) { double value = view->getFieldAs<double>(m_dimTypes[j].m_id, i); memcpy(static_cast<void*>(pointsPtr++), static_cast<void*>(&value), sizeof(double)); } } result = matPutVariable(m_matfile, "Points", points); if (result != 0) { std::stringstream ss; ss << "Could not write points to file: " << m_filename; throw pdal_error(ss.str()); } mxDestroyArray(points); }
void IO_MLabWriteDoubleImg(char *fileName, char *nameImg, double *img, int rows, int cols) { MATFile *fp; int i, j, dims[2]; double *ptr; mxArray *mxArr; dims[0] = rows; dims[1] = cols; fp = matOpen(fileName, "u"); mxArr = mxCreateNumericArray(2, dims, mxDOUBLE_CLASS, mxREAL); ptr = mxGetPr(mxArr); for(j=0; j<cols; j++) for(i=0; i<rows; i++) *(ptr ++) = img[i*cols + j]; /*mxSetName(mxArr, nameImg); matPutArray(fp, mxArr);*/ matPutVariable(fp, nameImg, mxArr); matClose(fp); mxDestroyArray(mxArr); }
template<size_t M, size_t N> void tomat(std::list<Eigen::Matrix<double, M, N> >list_matrix, std::string path, std::string var) { MATFile *file; void *p; mwSize *dims=new mwSize[3]; dims[0]=M; dims[1]=N; dims[2]=list_matrix.size(); file=matOpen(path.c_str(),"w"); mxArray *matrix; typename std::list<Eigen::Matrix<double, M, N> >::const_iterator itr_matrix=list_matrix.begin(); matrix=mxCreateNumericArray(3,dims, mxDOUBLE_CLASS, mxREAL); for(p=mxGetPr(matrix);itr_matrix!=list_matrix.end();itr_matrix++) { memcpy(p,itr_matrix->data(),sizeof(double)*M*N); p+=sizeof(double)*M*N; } matPutVariable(file, var.c_str(), matrix); }
void pendulum1d::State::save(const std::list<State> & states, std::string path) { MATFile *result; mxArray *theta; mxArray *omega; void *p; mwSize *dims=new mwSize[2]; result=matOpen(path.c_str(),"w"); std::list<State>::const_iterator it_state; it_state=states.begin(); dims[0]=1; dims[1]=states.size(); theta=mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxREAL); int n=0; for(p=mxGetPr(theta);it_state!=states.end();it_state++) { memcpy(p,&it_state->theta,sizeof(double)); p+=sizeof(double); } matPutVariable(result,"theta",theta); mxDestroyArray(theta); it_state=states.begin(); dims[0]=1; dims[1]=states.size(); omega=mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxREAL); for(p=mxGetPr(omega);it_state!=states.end();it_state++) { memcpy(p,&it_state->omega,sizeof(double)); p+=sizeof(double); } matPutVariable(result,"omega",omega); mxDestroyArray(omega); }
PetscErrorCode PetscViewerMatlabPutVariable(PetscViewer viewer,const char *name,void *mat) { PetscViewer_Matlab *ml = (PetscViewer_Matlab*)viewer->data; PetscFunctionBegin; matPutVariable(ml->ep,name,(mxArray*)mat); PetscFunctionReturn(0); }
void CMATLAB::matPut(string filename,const ArrayXd &X,string Xname) { MATFile *pmat=matOpen(filename,string("w")); if (!pmat) throw "CMATLAB::exportTo error: matOpen failed"; mxArray *pa=mxCreateDoubleMatrix((int)X.size(),1); if (!pa) throw "CMATLAB::exportTo error: mxCreateDoubleMatrix failed"; memcpy((void *)(mxGetPr(pa)), (void *)X.data(), X.size()*sizeof(double)); if (!matPutVariable(pmat,string("X"),pa)) throw "CMATLAB::exportTo error: matlab.matPutVariable failed"; mxDestroyArray(pa); if (!matClose(pmat)) throw "CMATLAB::exportTo error: matlab.matClose failed"; }
void writeMxArrayToSigFile(mxArray* mxTrial, mxArray* mxMeta, const SignalFileInfo *pSigFileInfo) { int error; // open the file MATFile* pmat = matOpen(pSigFileInfo->fileName, "w"); if(pmat == NULL) diep("Error opening MAT file"); // put variable in file error = matPutVariable(pmat, "trial", mxTrial); if(error) diep("Error putting variable in MAT file"); error = matPutVariable(pmat, "meta", mxMeta); if(error) diep("Error putting variable in MAT file"); // close the file matClose(pmat); }
void utility::writeMatlabFile(mat armaMatrix, const char *varname, const char *filename) { MATFile *pmat; mxArray *matlabMatrix; matlabMatrix = mxCreateDoubleMatrix(armaMatrix.n_rows, armaMatrix.n_cols, mxREAL); armadillo2matlabMatrix(&armaMatrix, matlabMatrix, armaMatrix.n_elem); pmat=matOpen(filename, "w"); matPutVariable(pmat, varname, matlabMatrix); matClose(pmat); }
bool CPPMaster::SavePolicyToMat(std::vector< std::vector<double> > policy, int tau){ // Command = force | pi | time // tau should also be saved, but it's included in the loop. // save a file: // File should also be in .mat format, if possible // name: Policy-%d.dat, where %d is tau // Should include BVP, Theta, and the tau associated. std::vector<double> forces = policy.at(0); std::vector<double> phi = policy.at(1); std::vector<double> time = policy.at(2); double* d_forces = forces.data(); double* d_phi = forces.data(); double* d_time = forces.data(); // The below code is a modification from an example given by MATLAB: // http://bit.ly/1dvUEGF MATFile *pmat; mxArray *pa_forces, *pa_phi, *pa_time; std::string name = "Policy-"+std::to_string(tau)+".mat"; const char *file = name.c_str(); pmat = matOpen(file, "w"); int status; // This is just for debugging purposes. pa_forces = mxCreateDoubleMatrix(1, forces.size(), mxREAL); pa_phi = mxCreateDoubleMatrix(1, phi.size(), mxREAL); pa_time = mxCreateDoubleMatrix(1, time.size(), mxREAL); memcpy((void *)(mxGetPr(pa_forces)), (void *)d_forces, sizeof(d_forces)); memcpy((void *)(mxGetPr(pa_phi)), (void *)d_phi, sizeof(d_phi)); memcpy((void *)(mxGetPr(pa_time)), (void *)d_time, sizeof(d_time)); status = matPutVariable(pmat, "forces", pa_forces); status = matPutVariable(pmat, "phi", pa_phi); status = matPutVariable(pmat, "time", pa_time); mxDestroyArray(pa_forces); mxDestroyArray(pa_phi); mxDestroyArray(pa_time); matClose(pmat); return true; }
int writeFs (MATFile *pmat, mxArray *pn, double fsHz) { /* fsHZ */ pn = mxCreateDoubleScalar(fsHz); if (pn == NULL) { printf("Unable to create mxArray with mxCreateDoubleMatrix\n"); return(1); } int status = matPutVariable(pmat, "fsHz", pn); if ((status) != 0) { printf("Error writing.\n"); return(EXIT_FAILURE); } return 0; }
int matFiles::writeXCORRMatFile(const char *file, std::vector<std::vector<std::shared_ptr<openAFE::twoCTypeBlock<double> > > >& left, double fsHz) { MATFile *pmat; /* Variables for mxArrays */ mxArray *pn_l = NULL, *pn2 = NULL; pmat = matOpen(file, "w"); if (pmat == NULL) { printf("Error creating file"); return(EXIT_FAILURE); } int status; /* EAR SIGNAL */ std::size_t leftChannels = left.size(); std::size_t leftLags = left[0].size(); uint32_t frameNumber = left[0][0]->array1.second + left[0][0]->array2.second; std::size_t ndim = 3, dims[3] = {frameNumber, leftChannels, leftLags }; pn_l = mxCreateNumericArray(ndim, dims, mxDOUBLE_CLASS, mxREAL ); if (pn_l == NULL) { printf("Unable to create mxArray with mxCreateDoubleMatrix\n"); return(1); } for ( std::size_t ii = 0 ; ii < leftChannels ; ++ii ) { for ( std::size_t jj = 0 ; jj < leftLags ; ++jj ) { memcpy( mxGetPr(pn_l) + frameNumber * ii + frameNumber * leftChannels * jj , left[ii][jj]->array1.first, left[ii][jj]->array1.second * sizeof(double) ); memcpy( mxGetPr(pn_l) + frameNumber * ii + frameNumber * leftChannels * jj + left[ii][jj]->array1.second, left[ii][jj]->array2.first, left[ii][jj]->array2.second * sizeof(double) ); } } status = matPutVariable(pmat, "leftOutput", pn_l); if ((status) != 0) { printf("Error writing.\n"); return(EXIT_FAILURE); } writeFs (pmat, pn2, fsHz); return(0); }
void utility::writeMatlabFile(mxArray *matlabMatrix, const char *varname, const char *filename) { MATFile *pmat; cout << "Opening matlab file..."; pmat=matOpen(filename, "w"); if (pmat == NULL) { cerr << "could not open matlab file for writing!" << endl; exit(EXIT_FAILURE); } cout << "done" << endl; cout << "Put variable into file..."; matPutVariable(pmat, varname, matlabMatrix); cout << "Closing file..."; matClose(pmat); cout << "done" << endl; }
int write_mat_matrix(const Matrix* M, const char* file_name, const char* varname) { MATFile* matf = NULL; mxArray* Mx = NULL; unsigned int i, j; double* data; int res; assert(file_name); assert(M); assert(varname); /* create mxArray */ Mx = mxCreateDoubleMatrix(M->n_rows, M->n_cols, mxREAL); if (!Mx) { exit(ERROR_MEM); /* TODO */ return ERROR_MEM; } /* copy data in column order! */ data = mxGetPr(Mx); for (j=0; j < M->n_cols; ++j) { for (i=0; i < M->n_rows; ++i) { *data = (double) matrix_get(M, i, j); ++data; } } /* let's open the file */ matf = matOpen(file_name, "wz" ); if(!matf) { return ERROR_IO; } /* put the variable in the .mat */ res = matPutVariable(matf, varname, Mx); if (res) { return ERROR_IO_MAT; } /* close the file and delete mxArray */ res = matClose(matf); assert(!res); mxDestroyArray(Mx); return 0; }
int matFiles::writeTDSMatFile(const char *file, std::shared_ptr<openAFE::twoCTypeBlock<double> > left, std::shared_ptr<openAFE::twoCTypeBlock<double> > right, double fsHz) { MATFile *pmat; /* Variables for mxArrays */ mxArray *pn_l = NULL, *pn2 = NULL; pmat = matOpen(file, "w"); if (pmat == NULL) { printf("Error creating file"); return(EXIT_FAILURE); } int status; /* EAR SIGNAL */ uint32_t leftSize = left->array1.second + left->array2.second; uint32_t rightSize = right->array1.second + right->array2.second; assert ( leftSize == rightSize ); pn_l = mxCreateDoubleMatrix(leftSize,2,mxREAL); if (pn_l == NULL) { printf("Unable to create mxArray with mxCreateDoubleMatrix\n"); return(1); } /* Left */ memcpy( mxGetPr(pn_l), left->array1.first, left->array1.second * sizeof(double) ); memcpy( mxGetPr(pn_l) + left->array1.second, left->array2.first, left->array2.second * sizeof(double) ); /* Right */ memcpy( mxGetPr(pn_l) + leftSize, right->array1.first, right->array1.second * sizeof(double) ); memcpy( mxGetPr(pn_l) + leftSize + right->array1.second, right->array2.first, right->array2.second * sizeof(double) ); status = matPutVariable(pmat, "outputSignals", pn_l); if ((status) != 0) { printf("Error writing.\n"); return(EXIT_FAILURE); } /* fsHZ */ writeFs (pmat, pn2, fsHz); return(0); }
void oz::matfile_write( const std::map<std::string, cpu_image> vars, const std::string& path ) { MATFile *pmat = 0; mxArray *pa = 0; try { pmat = matOpen(path.c_str(), "w"); if (!pmat) OZ_X() << "Creating file '" << path << "' failed!"; for (std::map<std::string, cpu_image>::const_iterator i = vars.begin(); i != vars.end(); ++i) { std::string name = i->first; std::replace(name.begin(), name.end(), '-', '_'); const oz::cpu_image& img = i->second; if (img.format() != FMT_FLOAT) OZ_X() << "Invalid format!"; pa = mxCreateNumericMatrix(img.w(), img.h(), mxSINGLE_CLASS, mxREAL); if (!pa) OZ_X() << "Creation of matrix for '" << name << "'failed!"; float *p = (float*)mxGetData(pa); for (unsigned i = 0; i < img.w(); ++i) { float *q = img.ptr<float>() + i; for (unsigned j = 0; j < img.h(); ++j) { *p++ = *q; q += img.pitch() / sizeof(float); } } if (matPutVariable(pmat, name.c_str(), pa) != 0) OZ_X() << "Putting variable '" << name << "'failed!"; mxDestroyArray(pa); } matClose(pmat); } catch (std::exception&) { if (pmat) matClose(pmat); if (pa) mxDestroyArray(pa); throw; } }
static void save2matfile(mxArray *A,string file,string varname){ //mxArray*mxA=array2mxArray(scores); //setDimensions(mxA,m,n); //save2matfile(mxA,"C:\\tim\\temp\\trash\\1.mat","A"); //matOpen doesn't work under windows unless some library is included #if defined(_WIN32) assert(0); #else MATFile *pmat = matOpen(file.c_str(), "w"); if (pmat == NULL) assert(0);//mexErrMsgTxt("error accessing mat file\n"); int status = matPutVariable(pmat, varname.c_str(), A); if (status != 0) assert(0);//mexErrMsgTxt("error writing mat file\n"); if (matClose(pmat) != 0) mexPrintf("Error closing file %s\n",file.c_str()); else mexPrintf("saved file %s\n",file.c_str()); #endif }
/*@C PetscViewerMatlabPutArray - Puts an array into the MATLAB viewer. Not collective: only processor zero saves the array Input Parameters: + mfile - the viewer . m,n - the dimensions of the array . array - the array (represented in one dimension) - name - the name of the array Level: advanced Notes: Only writes array values on processor 0. @*/ PetscErrorCode PetscViewerMatlabPutArray(PetscViewer mfile,int m,int n,const PetscScalar *array,const char *name) { PetscErrorCode ierr; PetscViewer_Matlab *ml = (PetscViewer_Matlab*)mfile->data; mxArray *mat; PetscFunctionBegin; if (!ml->rank) { ierr = PetscInfo1(mfile,"Putting MATLAB array %s\n",name); CHKERRQ(ierr); #if !defined(PETSC_USE_COMPLEX) mat = mxCreateDoubleMatrix(m,n,mxREAL); #else mat = mxCreateDoubleMatrix(m,n,mxCOMPLEX); #endif ierr = PetscMemcpy(mxGetPr(mat),array,m*n*sizeof(PetscScalar)); CHKERRQ(ierr); matPutVariable(ml->ep,name,mat); ierr = PetscInfo1(mfile,"Put MATLAB array %s\n",name); CHKERRQ(ierr); } PetscFunctionReturn(0); }
int matFiles::writeTFSMatFile(const char *file, std::vector<std::shared_ptr<openAFE::twoCTypeBlock<double> > >& left, std::vector<std::shared_ptr<openAFE::twoCTypeBlock<double> > >& right, double fsHz) { MATFile *pmat; /* Variables for mxArrays */ mxArray *pn_l = NULL, *pn_r = NULL, *pn2 = NULL; pmat = matOpen(file, "w"); if (pmat == NULL) { printf("Error creating file"); return(EXIT_FAILURE); } int status; /* EAR SIGNAL */ std::size_t leftSize = left.size(); std::size_t rightSize = right.size(); uint32_t frameNumber = left[0]->array1.second + left[0]->array2.second; assert ( leftSize == rightSize ); pn_l = mxCreateDoubleMatrix(frameNumber,leftSize,mxREAL); if (pn_l == NULL) { printf("Unable to create mxArray with mxCreateDoubleMatrix\n"); return(1); } for ( std::size_t ii = 0 ; ii < leftSize ; ++ii ) { memcpy( mxGetPr(pn_l) + frameNumber * ii, left[ii]->array1.first, left[ii]->array1.second * sizeof(double) ); memcpy( mxGetPr(pn_l) + frameNumber * ii + left[ii]->array1.second, left[ii]->array2.first, left[ii]->array2.second * sizeof(double) ); } status = matPutVariable(pmat, "leftOutput", pn_l); if ((status) != 0) { printf("Error writing.\n"); return(EXIT_FAILURE); } pn_r = mxCreateDoubleMatrix(frameNumber,rightSize,mxREAL); if ( pn_r == NULL ) { printf("Unable to create mxArray with mxCreateDoubleMatrix\n"); return(1); } for ( std::size_t ii = 0 ; ii < rightSize ; ++ii ) { memcpy( mxGetPr(pn_r) + frameNumber * ii, right[ii]->array1.first, right[ii]->array1.second * sizeof(double) ); memcpy( mxGetPr(pn_r) + frameNumber * ii + right[ii]->array1.second, right[ii]->array2.first, right[ii]->array2.second * sizeof(double) ); } status = matPutVariable(pmat, "rightOutput", pn_r); if ((status) != 0) { printf("Error writing.\n"); return(EXIT_FAILURE); } /* fsHZ */ writeFs (pmat, pn2, fsHz); return(0); }
int convert::matlab(){ #if MATLAB>0 MATFile *pmat; mxArray *time_mat, *eta_mat, *x_mat,*y_mat,*u_mat,*v_mat,*w_mat,*uz_mat,*vz_mat,*sigma_mat,*h_mat; const char *file = "OCW3D.mat"; //char str[BUFSIZE]; int status; // Open MAT file printf("Creating file %s...\n\n", file); pmat = matOpen(file, "w"); if (pmat == NULL) { printf("Error creating file %s\n", file); printf("(Do you have write permission in this directory?)\n"); return(EXIT_FAILURE); } // TIME time_mat = mxCreateDoubleMatrix(nt,1,mxREAL); if (time_mat == NULL) { printf("%s : Out of memory on line %d\n", __FILE__, __LINE__); printf("Unable to create mxArray.\n"); return(EXIT_FAILURE); } memcpy((void *)(mxGetPr(time_mat)),t,nt*sizeof(t)); status = matPutVariable(pmat, "t", time_mat); if (status != 0) { printf("%s : Error using matPutVariable on line %d\n", __FILE__, __LINE__); return(EXIT_FAILURE); } //// eta eta_mat = mxCreateDoubleMatrix(nx*ny,nt,mxREAL); if (eta_mat== NULL) { printf("%s : Out of memory on line %d\n", __FILE__, __LINE__); printf("Unable to create mxArray.\n"); return(EXIT_FAILURE); } memcpy((void *)(mxGetPr(eta_mat)), (void *)eta,nt*nx*ny*sizeof(eta)); status = matPutVariable(pmat, "eta", eta_mat); if (status != 0) { printf("%s : Error using matPutVariable on line %d\n", __FILE__, __LINE__); return(EXIT_FAILURE); } // h h_mat = mxCreateDoubleMatrix(nx*ny,1,mxREAL); if (h_mat== NULL) { printf("%s : Out of memory on line %d\n", __FILE__, __LINE__); printf("Unable to create mxArray.\n"); return(EXIT_FAILURE); } memcpy((void *)(mxGetPr(h_mat)), (void *)h,nx*ny*sizeof(h)); status = matPutVariable(pmat, "h", h_mat); if (status != 0) { printf("%s : Error using matPutVariable on line %d\n", __FILE__, __LINE__); return(EXIT_FAILURE); } // sigma sigma_mat = mxCreateDoubleMatrix(nz,1,mxREAL); if (sigma_mat== NULL) { printf("%s : Out of memory on line %d\n", __FILE__, __LINE__); printf("Unable to create mxArray.\n"); return(EXIT_FAILURE); } memcpy((void *)(mxGetPr(sigma_mat)), (void *)sigma,nz*sizeof(sigma)); status = matPutVariable(pmat, "sigma", sigma_mat); if (status != 0) { printf("%s : Error using matPutVariable on line %d\n", __FILE__, __LINE__); return(EXIT_FAILURE); } // x x_mat = mxCreateDoubleMatrix(nx,1,mxREAL); if (x_mat== NULL) { printf("%s : Out of memory on line %d\n", __FILE__, __LINE__); printf("Unable to create mxArray.\n"); return(EXIT_FAILURE); } memcpy((void *)(mxGetPr(x_mat)), (void *)x,nx*sizeof(x)); status = matPutVariable(pmat, "x", x_mat); if (status != 0) { printf("%s : Error using matPutVariable on line %d\n", __FILE__, __LINE__); return(EXIT_FAILURE); } // y y_mat = mxCreateDoubleMatrix(ny,1,mxREAL); if (y_mat== NULL) { printf("%s : Out of memory on line %d\n", __FILE__, __LINE__); printf("Unable to create mxArray.\n"); return(EXIT_FAILURE); } memcpy((void *)(mxGetPr(y_mat)), (void *)y,ny*sizeof(y)); status = matPutVariable(pmat, "y", y_mat); if (status != 0) { printf("%s : Error using matPutVariable on line %d\n", __FILE__, __LINE__); return(EXIT_FAILURE); } // u u_mat = mxCreateDoubleMatrix(nx*ny*nz,nt,mxREAL); if (u_mat== NULL) { printf("%s : Out of memory on line %d\n", __FILE__, __LINE__); printf("Unable to create mxArray.\n"); return(EXIT_FAILURE); } double *pointer; pointer = mxGetPr(u_mat); for (int index=0;index<nt*nx*ny*nz;index++){ pointer[index] = u[index];} status = matPutVariable(pmat, "u", u_mat); if (status != 0) { printf("%s : Error using matPutVariable on line %d\n", __FILE__, __LINE__); return(EXIT_FAILURE); } // v v_mat = mxCreateDoubleMatrix(nx*ny*nz,nt,mxREAL); if (v_mat== NULL) { printf("%s : Out of memory on line %d\n", __FILE__, __LINE__); printf("Unable to create mxArray.\n"); return(EXIT_FAILURE); } pointer = mxGetPr(v_mat); for (int index=0;index<nt*nx*ny*nz;index++){ pointer[index] = v[index];} status = matPutVariable(pmat, "v", v_mat); if (status != 0) { printf("%s : Error using matPutVariable on line %d\n", __FILE__, __LINE__); return(EXIT_FAILURE); } // w w_mat = mxCreateDoubleMatrix(nx*ny*nz,nt,mxREAL); if (w_mat== NULL) { printf("%s : Out of memory on line %d\n", __FILE__, __LINE__); printf("Unable to create mxArray.\n"); return(EXIT_FAILURE); } pointer = mxGetPr(w_mat); for (int index=0;index<nt*nx*ny*nz;index++){ pointer[index] = w[index];} status = matPutVariable(pmat, "w", w_mat); if (status != 0) { printf("%s : Error using matPutVariable on line %d\n", __FILE__, __LINE__); return(EXIT_FAILURE); } // uz uz_mat = mxCreateDoubleMatrix(nx*ny*nz,nt,mxREAL); if (uz_mat== NULL) { printf("%s : Out of memory on line %d\n", __FILE__, __LINE__); printf("Unable to create mxArray.\n"); return(EXIT_FAILURE); } pointer = mxGetPr(uz_mat); for (int index=0;index<nt*nx*ny*nz;index++){pointer[index] = uz[index]; } status = matPutVariable(pmat, "uz", uz_mat); if (status != 0) { printf("%s : Error using matPutVariable on line %d\n", __FILE__, __LINE__); return(EXIT_FAILURE); } // vz vz_mat = mxCreateDoubleMatrix(nx*ny*nz,nt,mxREAL); if (vz_mat== NULL) { printf("%s : Out of memory on line %d\n", __FILE__, __LINE__); printf("Unable to create mxArray.\n"); return(EXIT_FAILURE); } pointer = mxGetPr(vz_mat); for (int index=0;index<nt*nx*ny*nz;index++){ pointer[index] = vz[index]; } status = matPutVariable(pmat, "vz", vz_mat); if (status != 0) { printf("%s : Error using matPutVariable on line %d\n", __FILE__, __LINE__); return(EXIT_FAILURE); } /* clean up */ mxDestroyArray(time_mat); mxDestroyArray(eta_mat); mxDestroyArray(x_mat); mxDestroyArray(y_mat); mxDestroyArray(u_mat); mxDestroyArray(v_mat); mxDestroyArray(w_mat); mxDestroyArray(uz_mat); mxDestroyArray(vz_mat); mxDestroyArray(sigma_mat); mxDestroyArray(h_mat); if (matClose(pmat) != 0) { printf("Error closing file %s\n",file); return(EXIT_FAILURE); } return 1; #else return 0; #endif }
int main (int argc, char**argv) { if (argc < 3) { printf ("Usage:\n\nmih <infile> <outfile> [options]\n\n"); printf ("Options:\n"); printf (" -nMs <n1 n2 n3 ...> Set an array of multiples of 'one million items' to experiment with\n"); printf (" -nM <number> Set the index from the nMs array to be used for this run (1 is the first)\n"); printf (" -Q <number> Set the number of query points to use from <infile>, default all\n"); printf (" -B <number> Set the number of bits per code, default autodetect\n"); printf (" -m <number> Set the number of chunks to use, default 1\n"); printf ("\n"); return 0; } char *infile = argv[1]; char *outfile = argv[2]; UINT32 N = 0; int B = 0; int m = 1; UINT32 K = 100; int nM = 0; int NQ = 0; double *nMs = NULL; int nnMs = 0; for (int argnum = 3; argnum < argc; argnum++) { if (argv[argnum][0] == '-') { switch (argv[argnum][1]) { case 'B': B = atoi(argv[++argnum]); break; case 'K': K = atoi(argv[++argnum]); break; case 'n': if (!strcmp(argv[argnum], "-nMs")) { nMs = new double[100]; while (++argnum < argc) if (argv[argnum][0] != '-') { nMs[nnMs++] = atof(argv[argnum]); } else { argnum--; break; } } else if (!strcmp(argv[argnum], "-nM")) { nM = atoi(argv[++argnum]); } break; case 'Q': NQ = atoi(argv[++argnum]); break; case 'm': m = atoi(argv[++argnum]); break; default: printf ("Unrecognized Option or Missing Parameter when parsing: %s\n", argv[argnum]); return EXIT_FAILURE; } } else { printf ("Invalid Argument: %s\n", argv[argnum]); return EXIT_FAILURE; } } MATFile *ifp = NULL; mxArray *mxnMs = NULL; mxArray *mxret = NULL; /* Opening output file to read "ret" and "nMs" if available */ ifp = matOpen(outfile, "r"); if (ifp) { mxnMs = matGetVariable(ifp, "nMs"); mxret = matGetVariable(ifp, "ret"); double *nMs2 = (double*)mxGetPr(mxnMs); int nnMs2 = mxGetN(mxnMs); if (nMs != NULL) { if (nnMs != nnMs2) { printf("#nMs is different from the #nMs read from the output file %d vs. %d.\n", nnMs, nnMs2); return EXIT_FAILURE; } for (int i=0; i<nnMs; i++) if (int(nMs[i]*1.0e6) != int(nMs2[i] * 1.0e6)) { printf("nMs are different from the nMs read from the output file.\n"); return EXIT_FAILURE; } delete[] nMs; } nnMs = nnMs2; nMs = nMs2; matClose (ifp); } else { mxnMs = mxCreateNumericMatrix(1, nnMs, mxDOUBLE_CLASS, mxREAL); double *nMs2 = (double*)mxGetPr(mxnMs); for (int i=0; i<nnMs; i++) nMs2[i] = nMs[i]; delete[] nMs; nMs = nMs2; } if (mxret == NULL) { const char* ab[] = {"res", "nres", "stat", "wt", "cput", "vm", "rss", "m"}; mxret = mxCreateStructMatrix(1000, nnMs, 8, ab); } /* Done with initializing mxnMs and mxret and sanity checks */ /* Loading the codes and queries from the input file */ ifp = matOpen (infile, "r"); if (!ifp) { printf ("Failed to open input file. Aborting.\n"); return EXIT_FAILURE; } printf ("Loading codes... "); fflush (stdout); mxArray *mxcodes = matGetVariable (ifp, "B"); printf ("done.\n"); printf ("Loading queries... "); fflush (stdout); mxArray *mxqueries = matGetVariable (ifp, "Q"); printf ("done.\n"); matClose (ifp); /* Done with the inputs */ int dim1codes = mxGetM(mxcodes); int dim1queries = mxGetM(mxqueries); if (!B) B = mxGetM(mxcodes)*8; if (B % 8 != 0) { printf ("Non-multiple of 8 code lengths are not currently supported.\n"); return EXIT_FAILURE; } N = 1.0e6 * nMs[nM-1]; if (N) N = std::min ( (UINT32)N, (UINT32)mxGetN(mxcodes) ); if (NQ > 0) NQ = std::min( NQ, (int)mxGetN(mxqueries) ); else NQ = mxGetN (mxqueries); printf("nM = %d |", nM); printf(" N = %.0e |", (double)N); printf(" NQ = %d |", NQ); printf(" B = %d |", B); printf(" m = %d", m); printf("\n"); /* Run multi-index hashing for 1,10,100,1000 NN and store the required stats */ int mold = -1; mihasher* MIH = NULL; clock_t start0, end0; time_t start1, end1; qstat *stats = (qstat*) new qstat[NQ]; for (K = 1; K<=1000; K *= 10) { mxArray *mxresults = mxCreateNumericMatrix (K, NQ, mxUINT32_CLASS, mxREAL); mxArray *mxnumres = mxCreateNumericMatrix (B+1, NQ, mxUINT32_CLASS, mxREAL); mxArray *mxctime = mxCreateNumericMatrix (1, 1, mxDOUBLE_CLASS, mxREAL); mxArray *mxwtime = mxCreateNumericMatrix (1, 1, mxDOUBLE_CLASS, mxREAL); mxArray *mxvm = mxCreateNumericMatrix (1, 1, mxDOUBLE_CLASS, mxREAL); mxArray *mxrss = mxCreateNumericMatrix (1, 1, mxDOUBLE_CLASS, mxREAL); mxArray *mxstats = mxCreateNumericMatrix (6, NQ, mxDOUBLE_CLASS, mxREAL); UINT32 *numres = (UINT32*) mxGetPr (mxnumres); UINT32 *results = (UINT32*) mxGetPr (mxresults); double *ctime = (double*) mxGetPr (mxctime); double *wtime = (double*) mxGetPr (mxwtime); double *vm = (double*) mxGetPr (mxvm); double *rss = (double*) mxGetPr (mxrss); double *stats_d = (double*) mxGetPr (mxstats); /* if m changes from K to K */ if (mold != m) { if (MIH != NULL) { printf ("Clearing up... "); fflush (stdout); delete MIH; printf ("done. \r"); fflush (stdout); } MIH = new mihasher(B, m); printf ("Populating %d hashtables with %.0e entries...\n", m, (double)N); fflush (stdout); start1 = time(NULL); start0 = clock(); MIH->populate ( (UINT8*) mxGetPr(mxcodes), N, dim1codes); end0 = clock(); end1 = time(NULL); double ct = (double)(end0-start0) / (CLOCKS_PER_SEC); double wt = (double)(end1-start1); printf ("done. | cpu %.0fm%.0fs | wall %.0fm%.0fs\n", ct/60, ct-60*int(ct/60), wt/60, wt-60*int(wt/60)); // printf ("done. \r"); // fflush (stdout); } printf(" m = %2d |", m); printf(" K = %4d |", K); printf(" "); MIH->setK(K); printf("query... "); fflush (stdout); start1 = time(NULL); start0 = clock(); MIH->batchquery (results, numres, stats, (UINT8*) mxGetPr(mxqueries), NQ, dim1queries); end0 = clock(); end1 = time(NULL); *ctime = (double)(end0-start0) / (CLOCKS_PER_SEC) / NQ; *wtime = (double)(end1-start1) / NQ; process_mem_usage(vm, rss); *vm /= double(1024*1024); *rss /= double(1024*1024); printf ("done | cpu %.3fs | wall %.3fs | VM %.1fgb | RSS %.1fgb \n", *ctime, *wtime, *vm, *rss); int ind = 1000*(nM-1) + K-1; double *pstats_d = stats_d; for (int i=0; i<NQ; i++) { pstats_d[0] = stats[i].numres; pstats_d[1] = stats[i].numcand; pstats_d[2] = stats[i].numdups; pstats_d[3] = stats[i].numlookups; pstats_d[4] = stats[i].maxrho; pstats_d[5] = (double) stats[i].ticks / CLOCKS_PER_SEC; pstats_d += 6; } mxSetFieldByNumber(mxret, ind, 0, mxresults); mxSetFieldByNumber(mxret, ind, 1, mxnumres); mxSetFieldByNumber(mxret, ind, 2, mxstats); mxSetFieldByNumber(mxret, ind, 3, mxwtime); mxSetFieldByNumber(mxret, ind, 4, mxctime); mxSetFieldByNumber(mxret, ind, 5, mxvm); mxSetFieldByNumber(mxret, ind, 6, mxrss); mxSetFieldByNumber(mxret, ind, 7, mxCreateDoubleScalar(m)); mold = m; } printf ("Clearing up... "); fflush (stdout); delete MIH; printf ("done. \r"); fflush (stdout); /* Done with mulit-index hashing and storing the stats */ /* Opening the output file for writing the results */ MATFile *ofp = matOpen (outfile, "w"); if (!ofp) { printf ("Failed to create/open output file. Aborting.\n"); return EXIT_FAILURE; } printf("Writing results to file %s... ", outfile); fflush(stdout); matPutVariable(ofp, "nMs", mxnMs); matPutVariable(ofp, "ret", mxret); printf("done.\n"); matClose(ofp); /* Done with the output file */ delete[] stats; mxDestroyArray (mxnMs); mxDestroyArray (mxret); mxDestroyArray (mxcodes); mxDestroyArray (mxqueries); /* skip deleting nMs if it is initialized by new double[] */ return 0; }
int main(int argc, char *argv[]) { /* Command line options: */ static VString mat = NULL; static VBoolean funconly = FALSE; static VOptionDescRec options[] = { {"out", VStringRepn, 1, &mat, VRequiredOpt, 0, "Matfile"}, {"funconly", VBooleanRepn, 1, &funconly, VOptionalOpt, 0, "Functional data only (in one single 4D-object)"}, }; FILE *in_file; VAttrList in_list; VAttrListPosn posn; VImage src = NULL; VBit *bit_pp = NULL, *pbSRC = NULL; VShort *short_pp = NULL, *psSRC = NULL; VUByte *ubyte_pp = NULL, *puSRC = NULL; VFloat *float_pp = NULL, *pfSRC = NULL; VDouble *double_pp = NULL, *pdSRC = NULL; VString mode = NULL, name = NULL; mxArray *SRC = NULL; MATFile *fp; int n = 0, dims[4]; int bands = 0, rows = 0, cols = 0; char prg_name[100]; char ver[100]; getLipsiaVersion(ver, sizeof(ver)); sprintf(prg_name, "vtomat V%s", ver); fprintf(stderr, "%s\n", prg_name); /* Parse command line arguments and identify files: */ VParseFilterCmd(VNumber(options), options, argc, argv, &in_file,/* &out_file */ NULL); /* Read the input file */ in_list = VReadFile(in_file, NULL); if(!in_list) exit(1); /* strings */ mode = (VString)malloc(sizeof(char)); name = (VString)malloc(sizeof(char) * 50); strcpy(mode, "w"); fp = matOpen(mat, mode); if(funconly == TRUE) { /******************************************************************* * * * L O O P over objects in vista file * * * *******************************************************************/ n = 0; for(VFirstAttr(in_list, & posn); VAttrExists(& posn); VNextAttr(& posn)) { if(VGetAttrRepn(& posn) != VImageRepn) continue; VGetAttrValue(& posn, NULL, VImageRepn, & src); if(VPixelRepn(src) == VShortRepn) { if(bands < 2) bands = VImageNBands(src); if(rows < 2) rows = VImageNRows(src); if(cols < 2) cols = VImageNColumns(src); if(bands != VImageNBands(src)) VError("Different bands in functional objects"); if(rows != VImageNRows(src)) VError("Different rows in functional objects"); if(cols != VImageNColumns(src)) VError("Different cols in functional objects"); n++; } } /*dimensions */ dims[3] = n; dims[2] = bands; dims[1] = rows; dims[0] = cols; SRC = mxCreateNumericArray(4, dims, mxINT16_CLASS, mxREAL); psSRC = (VShort *) mxGetPr(SRC); /* copy data to SRC */ for(VFirstAttr(in_list, & posn); VAttrExists(& posn); VNextAttr(& posn)) { if(VGetAttrRepn(& posn) != VImageRepn) continue; VGetAttrValue(& posn, NULL, VImageRepn, & src); if(VPixelRepn(src) == VShortRepn) { short_pp = (VShort *) VPixelPtr(src, 0, 0, 0); memcpy(psSRC, short_pp, sizeof(VShort) * dims[0] * dims[1] * dims[2]); psSRC += dims[0] * dims[1] * dims[2]; } } /* save data into file */ if(matPutVariable(fp, "fnc", SRC)) VError("Could not save data in MATLAB file"); /* destroy array */ mxDestroyArray(SRC); } else { /******************************************************************* * * * L O O P over objects in vista file * * * *******************************************************************/ n = 0; for(VFirstAttr(in_list, & posn); VAttrExists(& posn); VNextAttr(& posn)) { if(VGetAttrRepn(& posn) != VImageRepn) continue; VGetAttrValue(& posn, NULL, VImageRepn, & src); /*dimensions */ dims[3] = 1; dims[2] = VImageNBands(src); dims[1] = VImageNRows(src); dims[0] = VImageNColumns(src); sprintf(name, "obj%d\0", n); /* Bit ONLY */ if(VPixelRepn(src) == VBitRepn) { SRC = mxCreateNumericArray(3, dims, mxLOGICAL_CLASS, mxREAL); pbSRC = (VBit *) mxGetPr(SRC); bit_pp = (VBit *) VPixelPtr(src, 0, 0, 0); memcpy(pbSRC, bit_pp, sizeof(VBit) * dims[0] * dims[1] * dims[2]); } /* Short ONLY */ if(VPixelRepn(src) == VShortRepn) { SRC = mxCreateNumericArray(3, dims, mxINT16_CLASS, mxREAL); psSRC = (VShort *) mxGetPr(SRC); short_pp = (VShort *) VPixelPtr(src, 0, 0, 0); memcpy(psSRC, short_pp, sizeof(VShort) * dims[0] * dims[1] * dims[2]); } /* UByte ONLY */ if(VPixelRepn(src) == VUByteRepn) { SRC = mxCreateNumericArray(3, dims, mxUINT8_CLASS, mxREAL); puSRC = (VUByte *) mxGetPr(SRC); ubyte_pp = (VUByte *) VPixelPtr(src, 0, 0, 0); memcpy(puSRC, ubyte_pp, sizeof(VUByte) * dims[0] * dims[1] * dims[2]); } /* Float ONLY */ if(VPixelRepn(src) == VFloatRepn) { SRC = mxCreateNumericArray(3, dims, mxSINGLE_CLASS, mxREAL); pfSRC = (VFloat *) mxGetPr(SRC); float_pp = (VFloat *) VPixelPtr(src, 0, 0, 0); memcpy(pfSRC, float_pp, sizeof(VFloat) * dims[0] * dims[1] * dims[2]); } /* Double ONLY */ if(VPixelRepn(src) == VDoubleRepn) { SRC = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL); pdSRC = (VDouble *) mxGetPr(SRC); double_pp = (VDouble *) VPixelPtr(src, 0, 0, 0); memcpy(pdSRC, double_pp, sizeof(VDouble) * dims[0] * dims[1] * dims[2]); } /* save data into file */ if(matPutVariable(fp, name, SRC)) VError("Could not save data in MATLAB file"); /* destroy array */ mxDestroyArray(SRC); n++; } } /* Terminate */ matClose(fp); return 0; }
bool mat_save_multi_array_vec2(MATFile *f, QString qsVarName, const std::vector<std::vector<Array> > &vvA) { assert(f != 0); mwSize cell_ndim = 2; mwSize cell_dims[2]; assert(vvA.size() > 0); uint N1 = vvA.size(); uint N2 = vvA[0].size(); cell_dims[0] = N1; cell_dims[1] = N2; mxArray *CA = mxCreateCellArray(cell_ndim, cell_dims); assert(CA != 0); for (uint i1 = 0; i1 < N1; ++i1) { assert(vvA.size() > i1); assert(vvA[i1].size() == N2); for (uint i2 = 0; i2 < N2; ++i2) { /* init shape array */ const typename Array::size_type *shape_ptr = vvA[i1][i2].shape(); assert(shape_ptr != 0); boost::array<typename Array::size_type, Array::dimensionality> array_shape; for (uint i = 0; i < Array::dimensionality; ++i) array_shape[i] = shape_ptr[i]; /* create array of the same shape as initial array with data stored in fortran storage order */ Array B(array_shape, boost::fortran_storage_order()); B = vvA[i1][i2]; const typename Array::element *data2 = B.data(); assert(data2 != 0); /* shape again, this time as mwSize array */ mwSize dims[Array::dimensionality]; for (uint i = 0; i < Array::dimensionality; ++i) dims[i] = array_shape[i]; mxArray *E = mxCreateNumericArray(Array::dimensionality, dims, mxSINGLE_CLASS, mxREAL); assert(E != 0); /* copy elements to matlab array */ size_t nElements = vvA[i1][i2].num_elements(); if (nElements > 0) { float *pE = (float *)mxGetPr(E); assert(pE != 0); for (uint idx = 0; idx < nElements; ++idx) { *pE = *(data2 + idx); ++pE; } } /* add element to cell array */ mwIndex subs[2]; subs[0] = i1; subs[1] = i2; mwIndex cell_idx = mxCalcSingleSubscript(CA, cell_ndim, subs); //std::cout << "cell index: " << cell_idx << std::endl; mxSetCell(CA, cell_idx, E); } } matPutVariable(f, qsVarName.toStdString().c_str(), CA); mxDestroyArray(CA); return true; }
/* Print the result trajectory that is attached to urdme_model to a mat/hdf5 file. The output trajectory will be stored in a variable/dataset named "U". */ int dump_results(urdme_model* model, char *filename, char *type){ /* IN PYURDME, THIS IS NEVER CALLED. IT IS ALWAYS USING HDF5. */ int Ndofs,tlen,nsol; int *U; U = model->U[0]; Ndofs = model->Ncells*model->Mspecies; tlen = model->tlen; nsol = model->nsol; #ifdef OUTPUT_MAT MATFile *output; mxArray *Uout; #ifndef URDME_OUTPUT_SPARSE Uout = mxCreateDoubleMatrix(Ndofs,tlen,mxREAL); double *data; data = mxGetPr(Uout); /* Dense output data */ for (i=0;i<Ndofs*model->tlen;i++){ data[i]=(double) U[i]; } #else /* If sparse output, we write the matrix on dictionary of keys (DOK) format. The application using this matrix will then have to convert to whatever format needed. the keys are (iU,jU) and values sU. To instantiate a sparse matrix in Matlab, load the output file and do >> U = sparse(iU,jU,sU,mU,nU); */ /* Count number of non-zeros */ int nnz = 0,nnz_col; for (i=0; i<Ndofs*tlen; i++) { if (U[i]>0.0) nnz++; } mxArray* iU = mxCreateDoubleMatrix(nnz,1,mxREAL); mxArray* jU = mxCreateDoubleMatrix(nnz,1,mxREAL); mxArray* sU = mxCreateDoubleMatrix(nnz,1,mxREAL); // Dimesions of the matrix, mU (row) and nU(col). In-house matlib does not have mxCreateScalar. mxArray* mU = mxCreateDoubleMatrix(1,1,mxREAL); double *dim; dim = mxGetPr(mU); dim[0] = (double)Ndofs; mxArray* nU = mxCreateDoubleMatrix(1,1,mxREAL); dim = mxGetPr(nU); dim[0] = (double)tlen; double *iUdata = mxGetPr(iU); double *jUdata = mxGetPr(jU); double *sUdata = mxGetPr(sU); nnz = 0; for (j=0; j<tlen; j++){ for (i=0;i<Ndofs;i++){ if (U[j*Ndofs+i]>0.0){ /* NOTE THE +1 HERE, MATLAB SPECIFIC INDEXING. */ iUdata[nnz] = (double)(i+1); jUdata[nnz] = (double)(j+1); sUdata[nnz] = (double)U[j*Ndofs+i]; nnz++; } } } #endif mxArray *Tspanout; Tspanout = mxCreateDoubleMatrix(1, model->tlen,mxREAL); double *tdata; tdata = mxGetPr(Tspanout); for(i=0;i<model->tlen;i++) tdata[i]=model->tspan[i]; #ifdef URDME_LIBMAT output = matOpen(filename,"w"); // using built in URDME mat read/write #else output = matOpen(filename,"w7.3"); // Possibly large files #endif if (output == NULL){ printf("Error: Could not write to output file: %s\n",filename); return(-1); } #ifndef URDME_OUTPUT_SPARSE matPutVariable(output,"U",Uout); matPutVariable(output,"tspan",Tspanout); #else matPutVariable(output,"iU",iU); matPutVariable(output,"jU",jU); matPutVariable(output,"sU",sU); matPutVariable(output,"mU",mU); matPutVariable(output,"nU",nU); matPutVariable(output,"tspan",Tspanout); #endif matClose(output); #ifndef URDME_OUTPUT_SPARSE mxDestroyArray(Uout); mxDestroyArray(Tspanout); #else mxDestroyArray(iU); mxDestroyArray(jU); mxDestroyArray(sU); mxDestroyArray(Tspanout); mxDestroyArray(mU); mxDestroyArray(nU); #endif #elif defined(OUTPUT_HDF5) /* Write the result as a HDF5 dataset/file */ hid_t h5_output_file; herr_t status; h5_output_file = H5Fcreate(filename,H5F_ACC_TRUNC, H5P_DEFAULT,H5P_DEFAULT); if (h5_output_file == NULL){ printf("Failed to write U matrix HDF5 file."); exit(-1); } hsize_t dims[2]; /* dataset dimensions */ dims[0] = Ndofs; dims[1] = tlen; // Write the result matrix to the file status = H5LTmake_dataset(h5_output_file,"/U",2,dims,H5T_NATIVE_INT,U); if (status != 0){ printf("Failed to write U matrix HDF5 file."); exit(-1); } // Write tspan to the file dims[0] = 1; dims[1] = tlen; status = H5LTmake_dataset(h5_output_file,"/tspan",2,dims,H5T_NATIVE_DOUBLE,model->tspan); if (status != 0){ printf("Failed to write tspan vector HDF5 file."); exit(-1); } status = H5Fclose(h5_output_file); if (status != 0){ printf("Failed to close output HDF5 file."); exit(-1); } #endif return 1; }
//---------------------- 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); } }
void quadrotor::State::save(const std::list<State> & states, std::string path) { MATFile *result; mxArray *R; mxArray *xq; mxArray *omega; mxArray *vq; void *p; mwSize *dims=new mwSize[3]; result=matOpen(path.c_str(),"w"); std::list<State>::const_iterator it_state; it_state=states.cbegin(); dims[0]=3; dims[1]=3; dims[2]=states.size(); R=mxCreateNumericArray(3,dims,mxDOUBLE_CLASS,mxREAL); for(p=mxGetPr(R);it_state!=states.cend();it_state++) { Mat3 R=it_state->g.block(0,0,3,3); memcpy(p,R.data(),sizeof(double)*dims[0]*dims[1]); p+=sizeof(double)*dims[0]*dims[1]; } matPutVariable(result,"R",R); mxDestroyArray(R); it_state=states.cbegin(); dims[0]=3; dims[1]=1; dims[2]=states.size(); xq=mxCreateNumericArray(3,dims,mxDOUBLE_CLASS,mxREAL); for(p=mxGetPr(xq);it_state!=states.cend();it_state++) { memcpy(p,it_state->g.block(0,3,3,1).data(),sizeof(double)*dims[0]*dims[1]); p+=sizeof(double)*dims[0]*dims[1]; } matPutVariable(result,"xq",xq); mxDestroyArray(xq); it_state=states.cbegin(); dims[0]=3; dims[1]=1; dims[2]=states.size(); vq=mxCreateNumericArray(3,dims,mxDOUBLE_CLASS,mxREAL); for(p=mxGetPr(vq);it_state!=states.cend();it_state++) { memcpy(p,it_state->v.tail(3).data(),sizeof(double)*dims[0]*dims[1]); p+=sizeof(double)*dims[0]*dims[1]; } matPutVariable(result,"vq",vq); mxDestroyArray(vq); it_state=states.cbegin(); dims[0]=3; dims[1]=1; dims[2]=states.size(); omega=mxCreateNumericArray(3,dims,mxDOUBLE_CLASS,mxREAL); for(p=mxGetPr(omega);it_state!=states.cend();it_state++) { memcpy(p,it_state->v.head(3).data(),sizeof(double)*dims[0]*dims[1]); p+=sizeof(double)*dims[0]*dims[1]; } matPutVariable(result,"omega",omega); mxDestroyArray(omega); }