Matlab API从c ++中读取.mat文件,使用STL容器 [英] Matlab API reading .mat file from c++, using STL container

查看:333
本文介绍了Matlab API从c ++中读取.mat文件,使用STL容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从c ++中读取一些.mat数据文件,我阅读了文档,但我想知道如何以干净,优雅的方式处理数据。使用std:vector(modest .mat文件大小(10M〜1G),但内存问题应该认真对待)

I have to read some .mat data files from c++, I read through the documentation, but I would like to know how to handle the data in a clean and elegant way, e.g. using std:vector(modest .mat file size(10M~1G), but memory issues should be taken seriously)

我的函数是sth like:

My function is sth like:

#include <stdio.h>
#include "mat.h"
#include <vector>

int matread(const char *file, const vector<double>& pdata_v) {

MATFile *pmat;

pmat=matOpen("data.mat","r");
if (pmat == NULL) {
    printf("Error opening file %s\n", file);
    return(1);
}
mxArray *pdata = matGetVariable(pmat, "LocalDouble");

// pdata -> pdata_v

mxDestroy pa1;  // clean up
return 0;
}

所以,问题是,如何从mxArray * pdata

so, the question is, how can I make a copy from mxArray *pdata array to vector pdata_v efficiently and safely?

推荐答案

这里是使用MAT-API的示例:

Here is an example of using the MAT-API:

#include "mat.h"
#include <iostream>
#include <vector>

void matread(const char *file, std::vector<double>& v)
{
    // open MAT-file
    MATFile *pmat = matOpen(file, "r");
    if (pmat == NULL) return;

    // extract the specified variable
    mxArray *arr = matGetVariable(pmat, "LocalDouble");
    if (arr != NULL && mxIsDouble(arr) && !mxIsEmpty(arr)) {
        // copy data
        mwSize num = mxGetNumberOfElements(arr);
        double *pr = mxGetPr(arr);
        if (pr != NULL) {
            v.resize(num);
            v.assign(pr, pr+num);
        }
    }

    // cleanup
    mxDestroyArray(arr);
    matClose(pmat);
}

int main()
{
    std::vector<double> v;
    matread("data.mat", v);
    for (size_t i=0; i<v.size(); ++i)
        std::cout << v[i] << std::endl;
    return 0;
}



首先我们构建独立程序,并创建一些测试数据作为MAT-档案:

First we build the standalone program, and create some test data as a MAT-file:

>> mex -client engine -largeArrayDims test_mat.cpp

>> LocalDouble = magic(4)
LocalDouble =
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

>> save data.mat LocalDouble

现在我们运行程序:

C:\> test_mat.exe
16 
5 
9 
4 
2 
11 
7 
14 
3 
10 
6 
15 
13 
8 
12 
1 

这篇关于Matlab API从c ++中读取.mat文件,使用STL容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆