How can I create a function to access substructure values?

MathWorks Example.png
I'd like to write a function which can access the values of a substructure. For example, if I have structure (USA), containing another (states) then values within that substructure, I know I could access the GDP of the state PA through:
USA.PA.GDP
How can I create a generic function, GetGDP so that I can get the same result by
GetGDP(PA).
Similarly, I could enter any state (i.i MD or CA) and return the GDP of that given state.
This is a simplified example of a more complex system, but this is the fundamental challenge I am facing

 採用された回答

Fangjun Jiang
Fangjun Jiang 2019 年 1 月 11 日

1 投票

Using dynamic field names, you don't even need the function. But if you do, it is quite simple.
structName.(dynamicExpression)
USA.PA.GDP=1
USA.MD.GDP=2;
USA.PA.GDP
getGDP(USA,'PA')
function out=getGDP(StructVar,StateName)
out=StructVar.(StateName).GDP;
end

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeSpecialized Power Systems についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by