MAT File I/O 库txt文件生成mat格式

5 篇文章 0 订阅

获取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是压缩格式

http://zlib.net/

编译方式和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上运行同样方式



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值