2

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.

nabeel
  • 159
  • 2
  • 3
  • 13
  • 1
    By default MATLAB will write integers as double-precision floats, not as integers. That could be your problem but it's impossible to tell since you give no information on your code. Another solution would be to write your .mat file as version 7.3 (add '-v7.3' to the save call). This will then write the file as an HDF5 file and you can use the mature open-source HDF5 C++ API to read the data. – Justin Apr 04 '16 at 11:34
  • @Justin thank you for the response. I have updated the question and include my code. Could you please see the code if I am missing something in the code? – nabeel Apr 04 '16 at 11:57

1 Answers1

2

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.

mkamthan
  • 2,331
  • 3
  • 17
  • 23
nabeel
  • 159
  • 2
  • 3
  • 13