Most "MATLABesque" way to create mutable nested key value structure

12 Ansichten (letzte 30 Tage)
Just started learning MATLAB and have a background in Python. It seems that containers.Map() is the MATLAB structure most analagous to a python dictionary object but from what I can tell it isn't really optimized for modifying nested structures. For example:
>>>test = containers.Map('food', containers.Map())
>>>test('food')('hotdog')='yummy'
Returns
Error: ()-indexing must appear last in an index expression.
While the same syntax for a non-nested structure works fine:
>>>test = containers.Map('food','hotdog')
>>>test('drinks')='beer'
I realize that MATLAB can read/write JSON files directly but that isn't a very elegant solution. What is the "correct" MATLAB data structure for storing nested key value paired data?

Akzeptierte Antwort

TADA
TADA am 30 Nov. 2018
Bearbeitet: TADA am 30 Nov. 2018
If you don't mind the parser restrictions on keys you can use structs, which are basically dictionaries
you can access the values using .() notation if you need to use a string:
x = struct();
x.a = 10;
x.b = 1:10;
x.c = 'blah blah blah'
x =
struct with fields:
a: 10
b: [1 2 3 4 5 6 7 8 9 10]
c: 'blah blah blah'
% now using .() notation:
x.('a') = 10;
x.('b') = 1:10;
x.('c') = 'blah blah blah'
x =
struct with fields:
a: 10
b: [1 2 3 4 5 6 7 8 9 10]
c: 'blah blah blah'
% now for nested stuff:
x.s.a = 10;
y = x.('s').('a')
y =
10
% invalid field names:
x.('#$%') = 10
Invalid field name: '#$%'.
naturally you can use either dot indexing or .() notation to set or get whatever

Weitere Antworten (1)

Walter Roberson
Walter Roberson am 30 Nov. 2018
fetch the nested item and store it in aa variable. Modify. Store the modified version in the top level container .
MATLAB does not generally permit indexing of the results of computation but has an exception for dot indexing of java. This is not a general exception, but {} indexing has some leeway . For example {} indexing of tables and string objects probably gets closer to computation than static addressing , but the results are indexable .

Kategorien

Mehr zu Call Python from MATLAB finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by