簡體   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