获取MAT File I/O文件路径
https://sourceforge.net/projects/matio/?source=typ_redirect
配置
在Linux下
1、解压mat_1.5.8文件
2、运行./configure
3、make
4、make check
5、make install
不过在运行configure时候看打印出的log是否支持MATv7.3,若不支持,则进行脚本修改
# Check whether --with-hdf5 was given.
if test "${with_hdf5+set}" = set; then :
withval=$with_hdf5; HDF5_DIR=${withval}
else
HDF5_DIR=/home/huashui.liu/mat/local
fi
同样也需要查看zlib是否支持,若不支持也需要进行路径修改
运行mat需要zlib库支持,zlib是压缩格式
编译方式和mat编译一样
默认情况生成的mat格式的版本是v5的 ,若想生成v7.3版本,需要使用HDF5库支持,
https://www.hdfgroup.org/HDF5/release/obtainsrc.html#conf
按照INSTALL file编译
测试生成二维矩阵
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include "matio.h"
#include <stdio.h>
#include <string.h>
#define CELLSIZE 2
int main(int argc, char *argv[])
{
char msg[1024];
long long colnum=0,rownum=0;
char *tp;
int row=0,col=0,n=0; //row col;
double *b;
mat_t *matfp;
matvar_t *matvar;
size_t dims[2] = {0,0};
//Read file get col number
FILE *fp=fopen("liushuia.txt","r");
if(fp==NULL)
{
printf("Read file failed\n");
return 0;
}
fgets(msg,1024,fp);
tp=strtok(msg,"\n ' '");
while(tp!=NULL)
{
colnum++;
tp=strtok(NULL,"\n ' '");
}
while(!feof(fp)){
fgets(msg,1024,fp);
rownum++;
}
dims[0] = rownum;
dims[1] = colnum;
printf("Start ................rownum=%ld\n",rownum);
b=(double*)malloc(sizeof(double)*rownum*colnum); //malloc memory restore message
if(b==NULL)
{
printf("malloc failed...%ld\n",colnum);
return 0;
}
rewind(fp);
while(!feof(fp))
{
for(;row<rownum;row++)
{
fgets(msg,1024,fp);
tp=strtok(msg,"\n ' '");
for(col=0;col<colnum;col++)
{
if(tp!=NULL)
{
b[col*rownum+row]=atof(tp);
}
tp=strtok(NULL,"\n ' '");
}
printf("row=%d\n",row);
}
fgets(msg,1024,fp);
}
//make mat
matfp = Mat_CreateVer("testa.mat",NULL,MAT_FT_DEFAULT);
if ( NULL == matfp ) {
fprintf(stderr,"Error creating MAT file \"0718.mat\"\n");
return EXIT_FAILURE;
}
matvar = Mat_VarCreate("x",MAT_C_DOUBLE,MAT_T_DOUBLE,2,dims,b,0);
if ( NULL == matvar ) {
fprintf(stderr,"Error creating variable for 'x'\n");
} else {
Mat_VarWrite(matfp,matvar,MAT_COMPRESSION_ZLIB);
Mat_VarFree(matvar);
}
free(b);
Mat_Close(matfp);
printf("Mat End .......\n");
getchar();
return 0;
}
由于内存限制,当txt文件很大时候,申请内存可能不够,另外Mat_varCreate申请的内存也要受到限制,看看mat.c源文件Mat_VarCreate实现,
在vs上运行同样方式