繁体   English   中英

将数据从matlab文件读入C语言

[英]Reading data from matlab files into C

我正在尝试学习如何使用C API来读取Matlab .mat文件,但它没有按照我的预期工作:

我想打开一个名为test.mat的非常简单的.mat文件,从文件中读取一个值并将其存储在C变量中。 我使用以下命令在Matlab中创建了test.mat

> value = 3;
> save ("test.mat", "value")

下面是我的C代码,它甚至没有编译 - 编译器似乎没有找到头文件。 请参阅下面的编译器输出代码。 我在这做错了什么?

码:

#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;
}

编译器输出:

$ 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

(-I标志在我的makefile CPPFLAGS=-I/usr/local/MATLAB/R2011a/extern/include/行指定,我已经验证该目录是否存在并包含头文件mat.hmatrix.h )。

更新:
我发现我需要链接的库是libmat.solibmx.so (根据这篇MathWorks帮助文章 ),位于我的系统上的/usr/local/MATLAB/R2011a/bin/glnxa64/ 因此我将makefile更新为:

CPPFLAGS =-I/usr/local/MATLAB/R2011a/extern/include/
LDFLAGS = -L/usr/local/MATLAB/R2011a/bin/glnxa64 -l mat -l mx

现在,运行make会给出以下命令:

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

但是,我仍然得到同样的错误。 有任何想法吗?

这是链接器故障,而不是编译器故障(与-I编译器选项无关)。 您需要使用-L标志指定matlab .so文件所在的目录,并在指定matlab库名称的编译器命令末尾添加-l<matlab-lib-name>选项。

例如:

cc -I / usr / local / MATLAB / R2011a / extern / include / -L / usr / local / MATLAB / R2011a / lib animate_shot.c -o animate_shot -lmatlab

(我不知道.so所在的确切目录或matlab库的名称)


根据提供进一步信息的评论:

cc -I / usr / local / MATLAB / R2011a / extern / include / -L / usr / local / MATLAB / R2011a / bin / glnxa64 animate_shot.c -o animate_shot -lmat -lmx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM