Wednesday, February 4, 2009

Visual C++中创建MAT文件

Visual C++中创建MAT文件

Visual C++开发环境中,可以利用API函数库的MAT函数库,写入和读出MAT数据文件。通过这种数据文件的读写,可以有效地实现Visual C++环境同MATLAB开发环境的数据通信接口。以下matCreatCDemo.c文件为在Visual C++环境下实现MAT数据文件的读写操作,程序代码如下:
/*
* matCreatCDemo.c
*/
#include
#include
#include
#include "mat.h"
int main()
{
//MATFile文件定义,mxArray变量定义
const char *filename = "MatDemo.mat";
MATFile *file;
int flag1,flag2,flag3;
mxArray *pString, *pArray1, *pArray2;
// 初始数据定义
double a1[] = {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0};
double a2[] = {9.0, 4.0,5.4,6.4,3.2,1.5};
// 创建MAT文件
printf("Creating file %s...\n\n",filename);
file = matOpen(filename,"w");
if ( file == NULL )
{
printf("ERROR: Can not create file %s\n", filename);
return(EXIT_FAILURE);
}
// 创建字符串mxArray数据结构变量
pString = mxCreateString("This is the MAT demo in C lanuage! Enojy it~!");
if (pString == NULL)
{
printf("ERROR: Unable to create string!");
return(EXIT_FAILURE);
}
//创建矩阵mxArray数据结构变量
pArray1 = mxCreateDoubleMatrix(3,3,mxREAL);
pArray2 = mxCreateDoubleMatrix(2,3,mxREAL);
if( (pArray1 == NULL)(pArray2 ==NULL) )
{
printf("Error: Cannot create the double matrix!");
return(EXIT_FAILURE);
}
// 将初始数据拷贝给mxArray数据结构变量
memcpy( (void *)(mxGetPr(pArray1)), (void *)a1, sizeof(a1));
memcpy( (void *)(mxGetPr(pArray2)), (void *)a2, sizeof(a2));
// 向MAT文件中写入变量
flag1 = matPutVariable(file, "variableString", pString);
flag2 = matPutVariable(file, "variableDoubleMatrix1", pArray1);
flag3 = matPutVariable(file, "variableDoubleMatrix2", pArray2);
if(( flag1 != 0)(flag2 != 0)(flag3 != 0))
{
printf("Can not write variable into the file %s \n", filename);
return(EXIT_FAILURE);
}
// 释放内存空间
mxDestroyArray(pString);
mxDestroyArray(pArray1);
mxDestroyArray(pArray2);
// 关闭MAT文件
if(matClose(file) != 0)
{
printf("ERROR: Can not close %s file.\n",filename);
return(EXIT_FAILURE);
}
// 重新打开MAT文件
file = matOpen(filename, "r");
if (file == NULL)
{
printf("ERROR: Can not open file %s\n", filename);
return(EXIT_FAILURE);
}
// 读取MAT文件的数据变量
pArray1 = matGetVariable(file, "variableDoubleMatrix1");
pArray2 = matGetVariable(file, "variableDoubleMatrix2");
pString = matGetVariable(file, "variableString");
if ( (pArray1 == NULL) (pArray2 == NULL) (pString == NULL))
{
printf("ERROR: Can not reading variables from file %s\n",filename);
return(EXIT_FAILURE);
}
// 释放内存空间
mxDestroyArray(pArray1);
mxDestroyArray(pArray2);
mxDestroyArray(pString);
// 关闭MAT文件
if (matClose(file) != 0)
{
printf("ERROR: Can not close file %s\n",filename);
return(EXIT_FAILURE);
}

printf("Complete!\n");
return(EXIT_SUCCESS);
}
More details could be found in my published book:
MATLAB编程基础与典型应用
北京:人民邮电出版社,2008
ISBN:978-7-115-17932-6/TP

Pls contact me with Email:lhd06@mails.tsinghua.edu.cn

No comments: