I'm trying to learn how to use the C API to read Matlab .mat files, but it does not work as I expected:
I would just like to open a very simple .mat file called test.mat , read the value from the file and save it in the C variable. I created test.mat in Matlab using the following commands:
> value = 3; > save ("test.mat", "value")
Below is my C code that doesn't even compile - the compiler does not seem to find the header files. See below code for compiler output. What am I doing wrong here?
The code:
#include <stdlib.h> #include <stdio.h> #include <mat.h> #include <matrix.h> int main(int argc, char *argv[]) { double value; MATFile *datafile; datafile = matOpen("test.mat", "r"); mxArray *mxValue; mxValue = matGetVariable(datafile, "value"); matClose(datafile); value = *mxGetPr(mxArray); mxFree(mxArray); printf("The value fetched from the .mat file was: %f", value); return 0; }
Compiler Output:
$ make animate_shot cc -I/usr/local/MATLAB/R2011a/extern/include/ animate_shot.c -o animate_shot /tmp/cczrh1vT.o: In function `main': animate_shot.c:(.text+0x1a): undefined reference to `matOpen' animate_shot.c:(.text+0x2f): undefined reference to `matGetVariable' animate_shot.c:(.text+0x3f): undefined reference to `matClose' animate_shot.c:(.text+0x4b): undefined reference to `mxGetPr' animate_shot.c:(.text+0x5e): undefined reference to `mxFree' collect2: ld returned 1 exit status make: *** [animate_shot] Error 1
(the -I flag is on the line CPPFLAGS=-I/usr/local/MATLAB/R2011a/extern/include/ in my makefile and I checked that the directory exists and contains the mat.h and matrix.h header files).
UPDATE:
I found that the libraries I need to link are libmat.so and libmx.so (as per this MathWorks help article ), being in /usr/local/MATLAB/R2011a/bin/glnxa64/ on my system. So I updated my makefile:
CPPFLAGS =-I/usr/local/MATLAB/R2011a/extern/include/ LDFLAGS = -L/usr/local/MATLAB/R2011a/bin/glnxa64 -l mat -l mx
Now running make gives the following command:
cc -I/usr/local/MATLAB/R2011a/extern/include/ -L/usr/local/MATLAB/R2011a/bin/glnxa64 -l mat -l mx animate_shot.c -o animate_shot
However, I still get the same errors. Any ideas?
Tomas lycken
source share