我想學習如何使用C API來讀取Matlab的.mat
文件,但它不工作如我所料:讀取數據轉換成C
我想只需打開一個非常簡單的.mat
文件名爲test.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.h
和matrix.h
)。
UPDATE:
我發現,我需要鏈接的庫libmat.so
和libmx.so
(根據this MathWorks help article),我的系統上居住在/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
但是,我仍然得到同樣的錯誤。有任何想法嗎?
好的。我發現了* .so所在的位置('/ usr/local/MATLAB/R2011a/bin/glnxa64 /'),我想我[找出了這些庫的名稱](http://www.mathworks.se /help/techdoc/matlab_external/f19027.html)('libmat.so'和'libmx.so')。但是,我仍然無法編譯(獲得與以前相同的錯誤)。我已經更新了我的答案,並詳細說明了我所做的更改。 –
@TomasLycken,你的問題沒有更新。根據你所說的我已經更新了我的答案。 – hmjd
對不起 - 我寫了評論,開始寫更新並忘記點擊「保存」:P現在它在那裏。它似乎在做你在暗示的東西,但它仍然不起作用...... –