2015-05-14 40 views
3

我有一個matlab結構,其中幾個級別(例如a.b(j).c(i).d)。我想寫一個函數給我我想要的領域。如果結構只有一個級別,那將很容易:訪問複雜的matlab結構與函數/字符串

function x = test(struct, label1) 
    x = struct.(label1) 
end 

例如,如果我有結構a.b我可以通過:test('b')得到b。但是,這不適用於子字段,如果我有一個結構a.b.c我不能使用test('b.c')來訪問它。

有沒有什麼辦法可以將一個字符串與完整的字段名稱(帶點)傳遞給一個函數來檢索這個字段?還是有更好的方法來獲得我通過函數參數選擇的字段?

目標是?當然,對於一個字段名來說這將是一個無用的函數,但是我不想將字段名列表作爲參數來接收這些字段。

回答

1

您應該使用subsref功能:

function x = test(strct, label1) 
F=regexp(label1, '\.', 'split'); 
F(2:2:2*end)=F; 
F(1:2:end)={'.'}; 
x=subsref(strct, substruct(F{:})); 
end 

要訪問a.b.c你可以使用:

subsref(a, substruct('.', 'b', '.', 'c')); 

該測試函數首先使用.作爲分隔符分割輸入,並創建一個單元陣列F,其中每個其他元素都用.填充,然後將其元素作爲參數傳遞給substruct

請注意,如果有涉及structs的數組,它將得到第一個。對於a.b(i).c(j).d通過b.c.d將返回a.b(1).c(1).d。請參閱this question瞭解應該如何處理。

作爲一個附註,我將您的輸入變量struct更名爲strct,因爲struct是一個內置的MATLAB命令。

+0

對不起,這個解決方案很適合我,非常感謝! – lakerz

1

一種方法是創建一個自調用功能來做到這一點:

a.b.c.d.e.f.g = 'abc' 
value = getSubField (a, 'b.c.d.e.f.g') 

    'abc' 

function output = getSubField (myStruct, fpath) 
    % convert the provided path to a cell 
    if ~iscell(fpath); fpath = strread (fpath, '%s', 'delimiter', '.'); end 
    % extract the field (should really check if it exists) 
    output = myStruct.(fpath{1}); 
    % remove the one we just found 
    fpath(1) = []; 
    % if fpath still has items in it -> self call to get the value 
    if isstruct (output) && ~isempty(fpath) 
    % Pass in the sub field and the remaining fpath 
    output = getSubField (output, fpath); 
    end 
end 
+0

謝謝,它確實有效,但其他解決方案對我來說更加清晰。 – lakerz