2013-03-07 51 views
0

我想在matlab中使用結構。我有一個看起來像這樣的代碼:matlab中的結構:保存加載和工作

for i=1:10 
    a(i).p=some value; 
    a(i).q=some other value 
end 

我將它保存到mat文件中,但它似乎不成功。任何人都可以告訴我,如何保存這個結構並將其加載到文件/從文件中讀取特定類型的數據?例如,如何在加載結構後讀取字段a(i).q? 感謝

回答

5

保存和加載使用saveload

for ii=1:10 
    a(ii).p = rand(1); 
    a(ii).q = rand(1); 
end 
save('myMatFile.mat', 'a'); % note that the variable name is passed as a STRING 

clear a; % remove a from workspace. it is gone... 
exist('a', 'var'), % make sure a is gone 

load('myMatFile.mat'); % load 
exist('a', 'var'), % a now exists! Ta-da!! 

a(5).q, % access the fifth element of a 

PS
It is best not to use i and j as variables in Matlab

+0

要知道,MATLAB不能處理'保存( 'file.mat','一個。 p')'。你需要做'foo = a.p;保存('file.mat','foo')' – 2015-11-03 14:09:38

+0

@CarlWitthoft你可以'保存'('file.mat','a',' - struct')'獲得保存文件中的變量'p'。 – Shai 2015-11-03 14:24:47

+0

嗯,是的,'save('file.mat', - struct,'a','p')'會起作用,但爲什麼用戶必須去做解析器應該處理的事情呢? – 2015-11-03 15:54:53