c對mat文件的幾個操作,打開mat文件 讀取mat文件下的陣列,生成mat文件

#include "stdafx.h"
#include <stdlib.h>
#include "mat.h"
#include <iostream>

using namespace std;
int main()
{

    MATFile *pmat=NULL;
    MATFile *pmatFile = NULL;
    const char **dir;
    const char *file;
    //FILE *pp;
    const char *name;
    int         ndir;
    mxArray *pa;
    mxArray *pname;
    file = "E://alogrithmprogramming//C++//cmatdll//cmatdll//Y.mat";//雙反斜槓防止轉義  
    pmat = matOpen(file, "r");//打開文件,返回指向文件指針  
    //pp = matGetFp(pmat);
    if (pmat == NULL) {
        cout << "Error opening file" << endl;
        return 1;
    }

    dir = (const char **)matGetDir(pmat, &ndir); //ndir 表示mat文件中含有矩陣數目  
    if (dir == NULL) {
            cout << "Error reading directory of file" << endl;
            return(1);
    }

    else
    {
        cout << "opening file" << endl;
        cout << "Mat NUM: " << ndir << endl;
        for (int i = 0; i < ndir; i++)//mat文件下多個陣列名
            cout << dir[i] << endl;
    }

    pmat = matOpen(file, "r");//重新打開文件;  
    pa = matGetNextVariable(pmat, &name);//返回指向文件頭文件信息的指針,指針類型爲*mxArray;  
    cout << name << endl;//name 是矩陣的名字;  
    //pname=matGetVariable(pmat,name);// Read the array value for the specified variable name from a MAT-file.
    //cout << pname << endl;
    int ii = mxGetM(pa);//矩陣行數
    int jj = mxGetN(pa);//矩陣列數  
    cout << ii << "," << jj << endl;
    //double *pm = (double*)mxGetData(pa);//獲取矩陣數值,返回指向矩陣第一數值的指針;
    //cout << *(pm++)<< endl;
    //mxSetData(pa, pm);

    // 生成.mat文件   
    pmatFile = matOpen("A.mat", "w");
    matPutVariable(pmatFile, "A", pa);
    matClose(pmatFile);

    mxFree(dir);
    matClose(pmat);
    system("pause");
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章