c++matlabvisual-studio-2010mat-file

Reading Variable from .mat file in C++


I am making a program in which, I am doing some processing in Matlab and then saving the result in a .mat file using the following command in Matlab,

save data x;

let's suppose the value of x=2,

Now I am reading the same data.mat file from the C++ program in Visual Studio 2010. My program is compiling and I can also read the name of arrays and their dimensions perfectly, Now the problem is when I am using the following command, I cannot read the exact value of x. It is showing me some random values each time I run the program.

variable = matGetNextVariable(pmat, &name);

right now the value of the variable is 50779048.

Kindly guide me where I am making mistakes. the value of the variable should be 2 because I have saved 2 from the Matlab command.

I already check this question but it seems nobody answered it, Reading .mat file in C++

void main(int argc, char **argv)
{
    MATFile *pmat;
    const char* name=NULL;
    mxArray *pa;
    
    /* open the mat file and read its content */
    pmat = matOpen("data.mat", "r");
    if (pmat == NULL) 
    {
        printf("Error Opening File: \"%s\"\n", argv[1]);
        return;
    }
    
    /* Read in each array. */
    pa = matGetNextVariable(pmat, &name);
    while (pa!=NULL)
    {
        /*
        * Diagnose array pa
        */
        printf("\nArray %s has %d dimensions.", name, 
               mxGetNumberOfDimensions(pa));
        
        //print matrix elements
        printf("\ndata %d",pa);
        
        //get next variable
        pa = matGetNextVariable(pmat,&name);
        
        //printf("\ndata %d",pa);
        //destroy allocated matrix
        mxDestroyArray(pa);
    }
    
    matClose(pmat);
}

Thank you.


Solution

  • After doing a lot of searching again, I found the answer. Somebody already asked the question but in a different way, Following is the link to the answer, Matlab API reading .mat file from c++, using STL container, I hope that this is helpful.