2013-05-14 131 views
1

結構域我有問題訪問MATLAB結構的各個領域。我試圖將其轉換然而細胞時,它給我的錯誤:( 如何訪問每個字段有2個循環 我已經寫了下面的代碼:訪問基於結構名

a=load(goalMFile); 
struct_name=fieldnames(a); 
struct_cell=struct2cell(a); 
cellsz = cellfun(@size,struct_cell,'uni',false); 
ans=cellsz{:}; 
row=ans(1); 
col=ans(2); 
for counter1=1:row 
for counter2=1:col 
a.struct_name{(counter1-1)*counter2+counter2} % the error is Here 
end 

end 

我會很感激,如果有人可以幫助我。

回答

3

可以與s.(fname)其中fname是char變量動態訪問的結構,請注意()周圍fname

一個例子闡明:。

% Example structure 
s.A = 10; 
s.B = 20; 

% Retrieve fieldnames 
fnames = fieldnames(s); 

% Loop with numeric index 
for ii = 1:numel(fnames) 
    s.(fnames{ii}) 
end 

% ...or loop by fieldname directly 
for f = fnames' 
    s.(f{:}) 
end 
+0

+1你的回答對我幫助很大。我只想補充一點,這可以通過在字段名(這是在我的情況的字符串)排序操作方便地組合:對於tempFieldname =排序(字段名(S))」 ... – RobertG 2014-01-12 16:05:19