int MatFileIO::getNumberOfVariables() { Mat_Rewind(mat); // get back to first variable int count = 0; matvar_t * matvar = Mat_VarReadNextInfo(mat); while (matvar != NULL) { count++; matvar = Mat_VarReadNextInfo(mat); } Mat_VarFree(matvar); return count; }
// load a .mat matlab matrix // will load the first matrix (sparse or dense) in the file // returns 0 on success static int read_mat(char const *const filename, matrix_t *const A) { #ifndef HAVE_MATIO return 1; #else const int LOCAL_DEBUG = 0; mat_t* matfp; matfp = Mat_Open(filename, MAT_ACC_RDONLY); if(matfp == NULL) return 1; // failed to open file matvar_t* t; int more_data = 1; while (more_data) { t = Mat_VarReadNextInfo(matfp); if(t == NULL) { return 2; // no suitable variable found } // TODO decide if this is the one: if(t-> if(1) { more_data = 0; } else { // keep going Mat_VarFree(t); t = NULL; } } { // load the selected variable, including data Mat_Rewind(matfp); matvar_t* tt = Mat_VarRead(matfp, t->name); Mat_VarFree(t); t = tt; if(LOCAL_DEBUG) Mat_VarPrint(tt, 1); } // debug info if(LOCAL_DEBUG && t->name != NULL) printf("%s: loaded variable %s\n", filename, t->name); // checks and data handling int ret = 0; if(t->rank > 2 || t->rank <= 0) { // number of dimensions ret = 2; } else if(t->data_type != MAT_T_DOUBLE) { if(LOCAL_DEBUG) printf("data_type=%d\n",t->data_type); ret = 3; } else if(t->isComplex) { ret = 10; // TODO can't handle complex matrices yet } else if(t->isLogical) { ret = 11; // TODO can't handle logicals yet } else { if(t->rank == 1) { A->m = t->dims[0]; // rows A->n = 1; // cols } else { A->m = t->dims[0]; // rows A->n = t->dims[1]; // cols } A->sym = SM_UNSYMMETRIC; //if(t->data_type == MAT_T_DOUBLE) { A->data_type = REAL_DOUBLE; //} // TODO complex, single precision, various sized integers if(t->class_type == MAT_C_SPARSE) { // t.data = sparse_t in CSC format // Note that Matlab will save('-v4'...) a sparse matrix // to version 4 format without complaint but it appears // to be gibberish as far as MatIO is concerned sparse_t* st = t->data; A->nz = st->ndata; //st->nzmax has the actual size of the allocated st->data A->format = SM_CSC; // transfer the data pointer into our strucut // TODO check for negative values in ir/jc before throwing away their signs A->ii = (unsigned int*) st->ir; st->ir = NULL; A->jj = (unsigned int*) st->jc; st->jc = NULL; A->dd = st->data; st->data = NULL; } else if(t->class_type == MAT_C_DOUBLE) { A->nz = A->m * A->n; A->format = DCOL; // transfer the data pointer into our struct A->dd = t->data; t->data = NULL; } else { ret = 4; // unknown class of data structure } } // DEBUG if(LOCAL_DEBUG && validate_matrix(A) != 0) { ret = 50; fprintf(stderr, "problem loading .mat matrix file\n"); printf_matrix(" ", A); } // sanity checks // t.dims[] is don't-care // t.isGlobal is don't-care Mat_Close(matfp); Mat_VarFree(t); return ret; // success? #endif }