How to create an empty dictionary with a struct as value
조회 수: 42 (최근 30일)
이전 댓글 표시
I want to create a dictionary with a defined struct as the value. What i currently have is:
dict = dictionary(string.empty, struct(test={}));
The problem is that the empty dictionary throws an error when i try to access the struct it throws an error that the field name does not exist:
dict.values.test
I want that the dictionary behave like when you try to access an empty struct with a field. Is there any way so the dictionary remembers the field values?
댓글 수: 7
Paul
2022년 12월 9일
I still don't understand what the use case is for having an empty, configured dictionary where the value of the empty dictionary is a struct with a field. What would you do with that empty dictionary, which I guess is the same question asked by @Jan.
If we configure a dictionary with an empty string key and empty struct value
d = dictionary(string.empty,struct.empty)
we can subsequently add entries to the dictionary
d("a") = struct(test=1);
d("b") = struct(test=2);
d.values returns a struct array
d.values
which, in this case can be accessed as a struct and the values in the test field turned into an array via a comma separated list in the usual way
[d.values.test]
We can add an entry with a different type of value in the test field
d("c") = struct(test="foo")
d.values
d.values.test
We can even add a struct with a different field
d("d") = struct(other=100)
But now we can't access values as above because the struct values are different and can't themeselves be concateneated into a struct array
try
d.values
catch ME
disp('error')
end
But we can still get the values in a cell array
values(d,"cell")
답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!