最近開發(fā)的時候需要用c++讀取別人導(dǎo)出的matlab xxx.mat文件,記錄一下,以后省的查了~
#include <cmath>
#include "mat.h"
/*
* *dst : 目標(biāo)數(shù)組
* 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);//釋放內(nèi)存
matdata = NULL;
return 1;
}