C++ 读取matlab的.mat文件
2021-05-19 本文已影响0人
有事没事扯扯淡
最近开发的时候需要用c++读取别人导出的matlab xxx.mat文件,记录一下,以后省的查了~
#include <cmath>
#include "mat.h"
/*
* *dst : 目标数组
* file_path : xxx.mat文件路径
* matrixName : 读取文件中的变量名
* width / height : 读取的变量矩阵的宽和高
*/
bool ReadMatlabMat(double *dst, std::string filePath, std::string matrixName, int width, int height);
bool ReadMatlabMat(double *dst, std::string filePath, std::string matrixName, int width, int height)
{
MATFile* pmatFile = NULL;
mxArray* pMxArray = NULL;
double* matdata;
pmatFile = matOpen(filePath.c_str(), "r");//打开.mat文件
if (pmatFile == NULL)
{
return false;
}
pMxArray = matGetVariable(pmatFile, matrixName.c_str());//获取.mat文件里面名为matrixName的矩阵
matdata = (double*)mxGetData(pMxArray);//获取指针
matClose(pmatFile);//close file
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
dst[i * width + j] = double(matdata[j * height + i]);
}
}
mxDestroyArray(pMxArray);//释放内存
matdata = NULL;
return 1;
}