Most "MATLABesque" way to create mutable nested key value structure
조회 수: 9 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
TADA
2018년 11월 30일
편집: TADA
2018년 11월 30일
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
댓글 수: 0
추가 답변 (1개)
Walter Roberson
2018년 11월 30일
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 .
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!