Get data from multi-level struct using strings
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Niklas Nylén
am 25 Okt. 2017
Kommentiert: Niklas Nylén
am 6 Nov. 2017
I need to read data into matlab where a text file specifies the structure and index of the data and another file contains the data itself.
Currently the implementation is done using an eval statement, e.g.
eval(['data.' dataName '=value;'])
I would like to use parfor instead since there are a many large files to process but parfor doesn't allow eval. I tried fixing it by replacing the eval statement with:
data.(dataName) = value;
The issue I'm running into is that dataName specifies multiple levels of a struct, e.g. dataName = 'a.b.c', which gives me an error.
Is there any way to make this work?
0 Kommentare
Akzeptierte Antwort
Stephen23
am 25 Okt. 2017
Bearbeitet: Stephen23
am 25 Okt. 2017
You can use setfield and getfield with nested fields. Unfortunately the help description is quite vague on how to do this, but all you need to do is supply all the fieldnames individually:
>> val = 1;
>> name = 'a.b.c';
>> C = regexp(name,'\.','split');
>> data = setfield(struct(),C{:},val);
>> data.a.b.c
ans = 1
This is much more reliable than using eval, although it is possible that setting fields like this is also not permitted within a parfor loop, but it is worth a try.
7 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!