Creating a structure from a cell array with nested structure fields

9 ビュー (過去 30 日間)
Lexi Anderson
Lexi Anderson 2020 年 5 月 15 日
コメント済み: Stephen23 2020 年 5 月 15 日
I have a structure with a cell array with structure fields.
The structure is a.fields. where a.fields{1,1} = 'b.c', a.fields{2,1}='c.d'
The real info is longer with even more nested structures, but I need a way that takes those fields to create the actual structure. I am using a for loop to go through the list, and so far I have:
structure_name = a.fields{i;1};
name.structure_name = {some info};
with the final hope that name.b.c = {some info} and so on and so forth.
I considered a loop by separating the cell array strings by period and looping through as well but figured I would ask about the (hopefully) more simple way. Obviously Matlab doesnt like that the names have periods and its telling me that it's invalid.
I would appreciate any insight.

採用された回答

Stephen23
Stephen23 2020 年 5 月 15 日
編集済み: Stephen23 2020 年 5 月 15 日
Nope, that won't work.
Best approach: split on the period characters, then use setfield and getfield as appropriate:
S.field1.field2.field3 = 42;
P = 'field1.field2.field3';
pathPieces = split(P, '.');
theAnswer = getfield(S, pathPieces{:})
This example is taken from Steven Lord's answer here:
  2 件のコメント
Lexi Anderson
Lexi Anderson 2020 年 5 月 15 日
編集済み: Lexi Anderson 2020 年 5 月 15 日
Ah yeah, my next problem arises that the values for the new structure exist as a nxm matrix in the same inital matrix under a.values, so I get
"Reference to non-existent field, ' structure_name';
Stephen23
Stephen23 2020 年 5 月 15 日
"...the values for the new structure exist as a nxm matrix in the same inital matrix under a.values"
I see no reason why that should cause you any problem:
...
S = setfield(S, pathPieces{:}, a.values)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

製品


リリース

R2012a

Community Treasure Hunt

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

Start Hunting!

Translated by