美文网首页
C++ 读取matlab的.mat文件

C++ 读取matlab的.mat文件

作者: 有事没事扯扯淡 | 来源:发表于2021-05-19 10:55 被阅读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;
}

相关文章

网友评论

      本文标题:C++ 读取matlab的.mat文件

      本文链接:https://www.haomeiwen.com/subject/prfpjltx.html