lor*_*per 3 c++ matlab mex stdvector mat-file
我必须从c ++中读取一些.mat数据文件,我通过文档阅读,但我想知道如何以干净和优雅的方式处理数据,例如使用std:vector(modest .mat文件大小(10M~) 1G),但应该认真对待记忆问题)
我的功能是这样的:
#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;
}
Run Code Online (Sandbox Code Playgroud)
那么,问题是,如何有效和安全地从mxArray*pdata数组复制到矢量pdata_v?
以下是使用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.reserve(num); //is faster than resize :-)
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;
}
Run Code Online (Sandbox Code Playgroud)
首先,我们构建独立程序,并创建一些测试数据作为MAT文件:
>> 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
Run Code Online (Sandbox Code Playgroud)
现在我们运行程序:
C:\> test_mat.exe
16
5
9
4
2
11
7
14
3
10
6
15
13
8
12
1
Run Code Online (Sandbox Code Playgroud)
这是另一个想法。如果您对 C++ 代码中的裸指针过敏(顺便说一句,它们没有任何问题),您可以将裸指针包装在 boost 或 C++11 智能指针中,并使用删除器在mxDestroyArray()指针消失时调用正确的删除器的范围。这样您就不需要副本,您的用户代码也不需要知道如何正确释放。
typedef shared_ptr<mxArray> mxSmartPtr;
mxSmartPtr readMATarray(MATFile *pmat, const char *varname)
{
mxSmartPtr pdata(matGetVariable(pmat, varname),
mxDestroyArray); // set deleter
return pdata;
}
int some_function() {
mxSmartPtr pdata = readMATarray(pmat, "LocalDouble");
...
// pdata goes out of scope, and mxDestroy automatically called
}
Run Code Online (Sandbox Code Playgroud)
想法取自这里:http://www.boost.org/doc/libs/1_56_0/libs/smart_ptr/sp_techniques.html#incomplete
| 归档时间: |
|
| 查看次数: |
7508 次 |
| 最近记录: |