void open(const std::string& fileName) { m_fileName = fileName; m_pMatlabFile = matOpen(m_fileName.c_str(), "r"); if(!m_pMatlabFile) throw std::logic_error("Unable to open matlab file: " + fileName); }
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); }
pair<double, double> ProbabilisticWvmClassifier::loadSigmoidParamsFromMatlab(const string& thresholdsFilename) { // Load sigmoid stuff: double logisticA, logisticB; MATFile *pmatfile; mxArray *pmxarray; // =mat pmatfile = matOpen(thresholdsFilename.c_str(), "r"); if (pmatfile == 0) { throw invalid_argument("ProbabilisticWvmClassifier: Unable to open the thresholds-file: " + thresholdsFilename); } //TODO is there a case (when svm+wvm from same trainingdata) when there exists only a posterior_svm, and I should use this here? pmxarray = matGetVariable(pmatfile, "posterior_wrvm"); if (pmxarray == 0) { throw runtime_error("ProbabilisticWvmClassifier: Unable to find the vector posterior_wrvm. If you don't want probabilistic output, don't use a probabilistic classifier."); //logisticA = logisticB = 0; // TODO: Does it make sense to continue? } else { double* matdata = mxGetPr(pmxarray); const mwSize *dim = mxGetDimensions(pmxarray); if (dim[1] != 2) { throw runtime_error("ProbabilisticWvmClassifier: Size of vector posterior_wrvm !=2. If you don't want probabilistic output, don't use a probabilistic classifier."); //logisticA = logisticB = 0; // TODO: Does it make sense to continue? } else { logisticB = matdata[0]; logisticA = matdata[1]; } // Todo: delete *matdata and *dim?? mxDestroyArray(pmxarray); } matClose(pmatfile); return make_pair(logisticA, logisticB); }
//////////////////////////////////////////////////////////////////////// // // create a MAT file from a double passed in // int createMAT(const char *file, double *data, int datalen) { MATFile *pmat; mxArray *pa1; printf("Creating a .MAT file %s...\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(1); } pa1 = mxCreateDoubleMatrix(1,datalen,mxREAL); mxSetName(pa1, "iroro_debug_variable"); memcpy((char *)(mxGetPr(pa1)),(char *)data, 1*datalen*sizeof(double)); matPutArray(pmat, pa1); // clean up mxDestroyArray(pa1); if (matClose(pmat) != 0) { printf("Error closing file %s\n",file); return(1); } printf("Done\n"); return(0); }
void Transmission::LoadTransmission() { MATFile *matFileHandle; matFileHandle = matOpen(transmissionFileName, "r"); int numberOfDirectories; const char** directoryField= (const char** )matGetDir(matFileHandle, &numberOfDirectories); for(int i=0; i < numberOfDirectories; i++) { //std::cout<<directoryField[i]<<std::endl; mxArray* matArrayHandle = matGetVariable(matFileHandle, directoryField[i]); int numberOfRows = mxGetM(matArrayHandle); int numberOfColumns = mxGetN(matArrayHandle); double* matArrayAddress = mxGetPr(matArrayHandle); std::vector<double> transmissionDataEntry; for(int j=0;j<numberOfColumns;j++) { double matrixEntry = *(matArrayAddress+j); transmissionDataEntry.push_back(matrixEntry); } transmissionData.push_back(transmissionDataEntry); } gearRatios = transmissionData[0]; gearEfficiency = transmissionData[1]; gearInertias = transmissionData[2]; //std::cout<<"Transmission data successfully loaded"<<std::endl; if (matClose(matFileHandle) != 0) { std::cout<<"Error closing file"<<'\n'; } }
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); }
//-------------------------------------------- void read_solution(urdme_model *model, char*file){ mxArray *tspan,*U; MATFile *input_file; /* Open mat-file (read-only) */ input_file = matOpen(file,"r"); if (input_file == NULL){ printf("Failed to open mat-file '%s'.\n",file); return; } printf("read in '%s'\n'",file); /* Get U-matrix. */ init_sol(model,1); U = matGetVariable(input_file, "U"); if (U == NULL){ printf("No U solution variable in mat-file '%s'\n.",file); return; } int Usz = mxGetNumberOfElements(U); model->U[0] =(int *)malloc(Usz*sizeof(int)); double*Utmp = mxGetPr(U); model->nsol = 1; int i; for(i=0;i<Usz;i++){ model->U[0][i] = (int) Utmp[i]; } /* time span (optional) */ tspan = matGetVariable(input_file, "tspan"); if (tspan != NULL){ model->tspan = mxGetPr(tspan); model->tlen = mxGetNumberOfElements(tspan); } }
int test() { string str_file_name = "E:\\research\\working\\test_data\\test_gk_means.mat"; SMatrix<double> matZ; Vector<SMatrix<double> > vecmatDictionary; SMatrix<CodeType> mat_target; int num_dic; int is_initialize; int num_grouped; { MATFile* fp = matOpen(str_file_name.c_str(), "r"); SMART_ASSERT(fp).Exit(); mexConvert(matGetVariable(fp, "Z"), matZ); mexConvert(matGetVariable(fp, "all_D"), vecmatDictionary); mexConvert(matGetVariable(fp, "num_sub_dic_each_partition"), num_dic); mexConvert(matGetVariable(fp, "mat_compact_B"), mat_target); mxArray * para_encode = matGetVariable(fp, "para_encode"); mexConvert(mxGetField(para_encode, 0, "is_initialize"), is_initialize); mexConvert(mxGetField(para_encode, 0, "num_grouped"), num_grouped); matClose(fp); } IndexEncoding ie; ie.SetIsInitialize(is_initialize); ie.SetNumberGroup(num_grouped); ie.SetEncodingType(Type_gk_means); ie.SetEncodingType(Type_additive_quantization); SMatrix<CodeType> matRepresentation; matRepresentation.AllocateSpace(mat_target.Rows(), mat_target.Cols()); int num_selected_rows = 10; matRepresentation.AllocateSpace(num_selected_rows, mat_target.Cols()); ie.Solve(SMatrix<double>(matZ.Ptr(), num_selected_rows, matZ.Cols()), vecmatDictionary, num_dic, matRepresentation); PRINT << "good\n"; for (int i = 0; i < matRepresentation.Rows(); i++) { for (int j = 0; j < matRepresentation.Cols(); j++) { cout << (int)(matRepresentation[i][j]) << "\t"; } cout << "\n"; } //for (int i = 0; i < mat_target.Rows(); i++) //{ // for (int j = 0; j < mat_target.Cols(); j++) // { // SMART_ASSERT(matRepresentation[i][j] == mat_target[i][j]).Exit(); // } //} return 0; }
PetscErrorCode PetscViewerFileSetName_Matlab(PetscViewer viewer,const char name[]) { PetscViewer_Matlab *vmatlab = (PetscViewer_Matlab*)viewer->data; PetscFileMode type = vmatlab->btype; PetscFunctionBegin; if (type == (PetscFileMode) -1) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"Must call PetscViewerFileSetMode() before PetscViewerFileSetName()"); if (vmatlab->ep) matClose(vmatlab->ep); /* only first processor opens file */ if (!vmatlab->rank) { if (type == FILE_MODE_READ) vmatlab->ep = matOpen(name,"r"); else if (type == FILE_MODE_WRITE || type == FILE_MODE_WRITE) vmatlab->ep = matOpen(name,"w"); else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Unknown file type"); } PetscFunctionReturn(0); }
void IO_MLabCreateFile(char *fileName) { MATFile *fp; fp = matOpen(fileName, "w"); matClose(fp); }
void Machine::LoadMachine() { MATFile *matFileHandle; matFileHandle = matOpen(machineFileName, "r"); int numberOfDirectories; const char** directoryField= (const char** )matGetDir(matFileHandle, &numberOfDirectories); for(int i=0; i < numberOfDirectories; i++) { //std::cout<<directoryField[i]<<std::endl; mxArray* matArrayHandle = matGetVariable(matFileHandle, directoryField[i]); int numberOfRows = mxGetM(matArrayHandle); int numberOfColumns = mxGetN(matArrayHandle); double* matArrayAddress = mxGetPr(matArrayHandle); std::vector<std::vector<double>> machineData; for(int j=0;j<numberOfRows;j++) { std::vector<double> singleRowInArray; for(int k=0;k<numberOfColumns;k++) { double matrixEntry = *((matArrayAddress+j)+(k*numberOfRows)); singleRowInArray.push_back(matrixEntry); } machineData.push_back(singleRowInArray); } switch(i) { case 0: machineRPMRange = machineData[0]; //std::cout<<"machineRPMRange"<<std::endl; //PrintMachineData(machineRPMRange); break; case 1: machineTorqueRange = machineData[0]; //std::cout<<"machineTorqueRange"<<std::endl; //PrintMachineData(machineTorqueRange); break; case 2: machineEfficiencyData = machineData; //std::cout<<"machineEfficiencyData"<<std::endl; //PrintMachineData(machineEfficiencyData); break; case 3: rpmRangeForMaximumBrakeTorque = machineData[0]; //std::cout<<"rpmRangeForMaximumBrakeTorque"<<std::endl; //PrintMachineData(rpmRangeForMaximumBrakeTorque); break; case 4: machineMaximumBrakeTorque = machineData[0]; //std::cout<<"machineMaximumBrakeTorque"<<std::endl; //PrintMachineData(machineMaximumBrakeTorque); break; case 5: machineMaximumRegenerationTorque = machineData[0]; //std::cout<<"machineMaximumRegenerationTorque"<<std::endl; //PrintMachineData(machineMaximumRegenerationTorque); break; } } //std::cout<<"Data for machine "<<machineIndex<<" successfully loaded"<<std::endl; }
int read_mat_matrix(Matrix* M, const char* file_name, const char* varname) { MATFile* matf = NULL; mxArray* Mx = NULL; int res; unsigned int i,j; double* data; assert(file_name); assert(M); assert(varname); /* let's open the file*/ matf = matOpen(file_name, "r" ); if(!matf) { return ERROR_IO; } /* let's read the variable varname */ Mx = matGetVariable(matf, varname); if (!Mx) { matClose(matf); return ERROR_IO_MAT; } /* let's close the file */ res = matClose(matf); assert(!res); /* check: the variable must be a 2D matrix!! */ if(mxGetNumberOfDimensions(Mx) > 2) { matClose(matf); return ERROR_IO_MAT; } /* let's create the Matrix */ M->n_rows = (unsigned int) mxGetM(Mx); M->n_cols = (unsigned int) mxGetN(Mx); res = create_matrix(M, M->n_rows, M->n_cols); if (res) { mxDestroyArray(Mx); return res; } /* copy the data from the mxArray. Remember that matlab save in column-order!! */ data = mxGetPr(Mx); for (j=0; j < M->n_cols; ++j) { for (i=0; i < M->n_rows; ++i) { matrix_set(M, i, j, (float) *data); ++data; } } /* destroy mxArray*/ mxDestroyArray(Mx); return 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 m2pvme_upkarray_rest(int nlhs, mxArray *plhs[], int nrhs, mxArrayIn *prhs[]) { /*-------------------------------------------------------------------*/ MATFile *pmat; char fname[256]; mxArray *array_ptr; plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL); if((mxGetPr(plhs[1]))[0] = (double) pvme_upkarray_rest(&plhs[0],(char*)0)==1) { /* the data contains Matlab user defined objects! */ /* save and load this mxArray so as it will be recognized as an object */ /* object passing could be done by getting a default object from the workspace and then constructing the object in the workspace directly by using mxPutArray with each struct for each level... */ /* array_ptr = mexGetArray("def","base"); mxSetName(array_ptr, "defcopy"); mexPutArray(array_ptr, "base"); mxDestroyArray(array_ptr); */ sprintf(fname,"%s/dp_%d.mat",TMP_LOC,pvm_mytid()); /*printf(fname,"%s/dp_%d.mat",TMP_LOC,pvm_mytid());*/ pmat = matOpen(fname, "w"); if (pmat == NULL) { mexErrMsgTxt("m2libpvme:Error creating file for transferring object\n"); } mxSetName(plhs[0], "objsl"); if (matPutArray(pmat, plhs[0]) != 0) { mexErrMsgTxt("m2libpvme:m2pvme_upkarray_rest: Error saving temporary intermediate file for objects\n"); } if (matClose(pmat) != 0) { mexErrMsgTxt("m2libpvme:m2pvme_upkarray_rest:Error temporary intermediate file for object transfer\n"); } /* printf("class::::%s\n", mxGetClassName(plhs[0]));*/ if ( !( plhs[0] = mxCreateString(fname) ) ) mexErrMsgTxt("m2pvme_upkarray_rest(): mxCreateString() failed.\n"); } return; }
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); }
void CMATLAB::matGet(string filename,ArrayXd &X,string Xname) { MATFile *pmat=matOpen(filename,string("r")); if (!pmat) throw "CMATLAB::importFrom error: matlab.matOpen failed"; mxArray *pa=matGetVariable(pmat,Xname); if (!pa) throw "CMATLAB::importFrom error: matlab.matGetVariable failed"; int N=mxGetNumberOfElements(pa); if (N<=0) throw "CMATLAB::importFrom error: matlab.mxGetNumberOfElements failed"; X.resize(N); memcpy((void *)(mxGetPr(pa)), (void *)X.data(), sizeof((double *)X.data())); mxDestroyArray(pa); if (!matClose(pmat)) throw "CMATLAB::importFrom error: matlab.matClose failed"; }
pair<double, double> ProbabilisticSvmClassifier::loadSigmoidParamsFromMatlab(const string& logisticFilename) { Logger logger = Loggers->getLogger("classification"); #ifdef WITH_MATLAB_CLASSIFIER // Load sigmoid stuff: double logisticA = 0; double logisticB = 0; MATFile *pmatfile; mxArray *pmxarray; // =mat pmatfile = matOpen(logisticFilename.c_str(), "r"); if (pmatfile == 0) { throw runtime_error("ProbabilisticSvmClassifier: Unable to open the logistic file to read the logistic parameters (wrong format?):" + logisticFilename); } else { //read posterior_wrvm parameter for probabilistic WRVM output //TODO 2012: is there a case (when svm+wvm from same trainingdata) when there exists only a posterior_svm, and I should use this here? //TODO new2013: the posterior_svm is the same for all thresholds file, so the thresholds file is not needed for SVMs. The posterior_svm should go into the classifier.mat! pmxarray = matGetVariable(pmatfile, "posterior_svm"); if (pmxarray == 0) { std::cout << "[DetSVM] WARNING: Unable to find the vector posterior_svm, disable prob. SVM output;" << std::endl; // TODO prob. output cannot be disabled in the new version of this lib -> throw exception or log info message or something logisticA = logisticB = 0; } else { double* matdata = mxGetPr(pmxarray); const mwSize *dim = mxGetDimensions(pmxarray); if (dim[1] != 2) { std::cout << "[DetSVM] WARNING: Size of vector posterior_svm !=2, disable prob. SVM output;" << std::endl; // TODO same as previous TODO logisticA = logisticB = 0; } else { logisticB = matdata[0]; logisticA = matdata[1]; } // TODO delete *matdata and *dim? -> No I don't think so, no 'new' mxDestroyArray(pmxarray); } matClose(pmatfile); } return make_pair(logisticA, logisticB); #else string errorMessage("ProbabilisticSvmClassifier: Cannot load a Matlab classifier, library compiled without support for Matlab. Please re-run CMake with WITH_MATLAB_CLASSIFIER enabled."); logger.error(errorMessage); throw std::runtime_error(errorMessage); #endif }
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); }
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; }
void CCE::export_mat_file() {/*{{{*/ #ifdef HAS_MATLAB cout << "begin post_treatement ... storing cce_data to file: " << _result_filename << endl; MATFile *mFile = matOpen(_result_filename.c_str(), "w"); for(int i=0; i<_max_order; ++i) { char i_str [10]; sprintf(i_str, "%d", i); string idx_str = i_str; string label = "CCE" + idx_str; string label1 = "CCE" + idx_str+"_tilder"; size_t nClst = _spin_clusters.getClusterNum(i); mxArray *pArray = mxCreateDoubleMatrix(_nTime, nClst, mxREAL); mxArray *pArray1 = mxCreateDoubleMatrix(_nTime, nClst, mxREAL); size_t length= _nTime * nClst; memcpy((void *)(mxGetPr(pArray)), (void *) _cce_evovle_result[i].memptr(), length*sizeof(double)); memcpy((void *)(mxGetPr(pArray1)), (void *) _cce_evovle_result_tilder[i].memptr(), length*sizeof(double)); matPutVariableAsGlobal(mFile, label.c_str(), pArray); matPutVariableAsGlobal(mFile, label1.c_str(), pArray1); mxDestroyArray(pArray); mxDestroyArray(pArray1); } mxArray *pRes = mxCreateDoubleMatrix(_nTime, _max_order, mxREAL); mxArray *pRes1 = mxCreateDoubleMatrix(_nTime, _max_order, mxREAL); mxArray *pTime = mxCreateDoubleMatrix(_nTime, 1, mxREAL); size_t length= _nTime*_max_order; memcpy((void *)(mxGetPr(pRes)), (void *) _final_result_each_order.memptr(), length*sizeof(double)); memcpy((void *)(mxGetPr(pRes1)), (void *) _final_result.memptr(), length*sizeof(double)); memcpy((void *)(mxGetPr(pTime)), (void *) _time_list.memptr(), _nTime*sizeof(double)); matPutVariableAsGlobal(mFile, "final_result_each_order", pRes); matPutVariableAsGlobal(mFile, "final_result", pRes1); matPutVariableAsGlobal(mFile, "time_list", pTime); mxDestroyArray(pRes); mxDestroyArray(pRes1); mxDestroyArray(pTime); matClose(mFile); #endif }/*}}}*/
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; }
bool CPPMaster::CreateBVP(int tau, std::string file_name, std::vector<double> goal_pt){ double* x_data; double* y_data; double* z_data; int row_count; int col_count; // I: Read the file out into a form that we can use. MATFile *pmat; mxArray *pa; pmat = matOpen(file_name.c_str(), "r"); // Since we already know the fields, we can match them up ourselves. pa = matGetVariable(pmat, "xx"); x_data = mxGetPr(pa); pa = matGetVariable(pmat, "yy"); y_data = mxGetPr(pa); pa = matGetVariable(pmat, "zz"); z_data = mxGetPr(pa); pa = matGetVariable(pmat, "row_count"); row_count = int(*mxGetPr(pa)); pa = matGetVariable(pmat, "col_count"); col_count = int(*mxGetPr(pa)); double* start_point = new double[4]; start_point[0] = 1; start_point[1] = -.5; start_point[2] = PI/2; start_point[3] = 0; double* goal_point = goal_pt.data(); // I don't know how else to do this, 'cause I'm ig'nant. params_.Clear(); for (int ii=0; ii<4;ii++) { params_.add_start_param(start_point[ii]); params_.add_goal_param(goal_point[ii]); } for (int ii=0;ii<(row_count*col_count);ii++) { params_.add_x_data(x_data[ii]); params_.add_y_data(y_data[ii]); params_.add_z_data(z_data[ii]); } params_.set_col_count(col_count); params_.set_row_count(row_count); params_.set_tau(tau); }
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; } }
void Transmission::LoadTransmission() { MATFile *matFileHandle; matFileHandle = matOpen(transmissionFileName, "r"); int numberOfDirectories; const char** directoryField= (const char** )matGetDir(matFileHandle, &numberOfDirectories); for(int i=0; i < numberOfDirectories; i++) { std::cout<<directoryField[i]<<std::endl; mxArray* matArrayHandle = matGetVariable(matFileHandle, directoryField[i]); int numberOfRows = mxGetM(matArrayHandle); int numberOfColumns = mxGetN(matArrayHandle); double* matArrayAddress = mxGetPr(matArrayHandle); std::vector<double> transmissionDataEntry; for(int j=0;j<numberOfColumns;j++) { double matrixEntry = *(matArrayAddress+j); transmissionDataEntry.push_back(matrixEntry); } transmissionData.push_back(transmissionDataEntry); } std::cout<<"Transmission data successfully loaded"<<std::endl<<std::endl; }
void Buffer::LoadBuffer() { MATFile *matFileHandle; matFileHandle = matOpen(bufferFileName, "r"); int numberOfDirectories; if(matFileHandle==NULL) { std::cout<<"ERROR IN FILE OPENING"<<std::endl; } const char** directoryField= (const char** )matGetDir(matFileHandle, &numberOfDirectories); for(int i=0; i < numberOfDirectories; i++) { //std::cout<<directoryField[i]<<std::endl; mxArray* matArrayHandle = matGetVariable(matFileHandle, directoryField[i]); int numberOfRows = mxGetM(matArrayHandle); int numberOfColumns = mxGetN(matArrayHandle); double* matArrayAddress = mxGetPr(matArrayHandle); for(int j=0;j<numberOfColumns;j++) { double matrixEntry = *(matArrayAddress+j); bufferData.push_back(matrixEntry); } } maximumBufferLevel = bufferData[0]; //std::cout<<"Max. buffer level "<<maximumBufferLevel<<std::endl; minimumBufferLevel = bufferData[1]; //std::cout<<"Min. buffer level "<<minimumBufferLevel<<std::endl; maximumStateOfBuffer = bufferData[2]; //std::cout<<"Max. state of buffer "<<maximumStateOfBuffer<<std::endl; referenceStateOfBuffer = bufferData[3]; // A dummy reference is given to all buffers, Fuel Tanks and Batteries. For batteries, // this value is updated eat each step. It remains constant for fuel tanks. //std::cout<<"Min. allowed state of buffer "<<referenceStateOfBuffer<<std::endl; openCircuitVoltage = bufferData[4]; //std::cout<<"openCircuitVoltage "<<openCircuitVoltage<<std::endl; instantaneousBufferLevel=maximumStateOfBuffer*maximumBufferLevel; //bufferLevelOverMission.push_back(instantaneousBufferLevel); //std::cout<<"Inst. buffer level "<<instantaneousBufferLevel<<std::endl; //std::cout<<"Buffer data successfully loaded"<<std::endl; if (matClose(matFileHandle) != 0) { std::cout<<"Error closing file"<<'\n'; } }
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 }
void LoadMission(std::vector<std::vector<double>>& missionData) { MATFile *matFileHandle; matFileHandle = matOpen("data/MissionData.mat", "r"); int numberOfDirectories; const char** directoryField= (const char** )matGetDir(matFileHandle, &numberOfDirectories); //std::cout<<"Number of directories: "<<numberOfDirectories<<std::endl; for(int i=0; i < numberOfDirectories; i++) { //std::cout<<directoryField[i]<<std::endl; mxArray* matArrayHandle = matGetVariable(matFileHandle, directoryField[i]); int numberOfRows = mxGetM(matArrayHandle); int numberOfColumns = mxGetN(matArrayHandle); double* matArrayAddress = mxGetPr(matArrayHandle); std::vector<double> missionDataEntry; for(int j=0;j<numberOfColumns;j++) { double matrixEntry = *(matArrayAddress+j); missionDataEntry.push_back(matrixEntry); } missionData.push_back(missionDataEntry); } std::cout<<"Mission data successfully loaded"<<std::endl<<std::endl; }
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); }