Clear Filters
Clear Filters

How to create an empty dictionary with a struct as value

42 views (last 30 days)
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
Unrecognized field name "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 Comments
Paul
Paul on 9 Dec 2022
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)
d =
dictionary (stringstruct) with no entries.
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
ans = 2×1 struct array with fields:
test
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]
ans = 1×2
1 2
We can add an entry with a different type of value in the test field
d("c") = struct(test="foo")
d =
dictionary (stringstruct) with 3 entries: "a" ⟼ 1×1 struct "b" ⟼ 1×1 struct "c" ⟼ 1×1 struct
d.values
ans = 3×1 struct array with fields:
test
d.values.test
ans = 1
ans = 2
ans = "foo"
We can even add a struct with a different field
d("d") = struct(other=100)
d =
dictionary (stringstruct) with 4 entries: "a" ⟼ 1×1 struct "b" ⟼ 1×1 struct "c" ⟼ 1×1 struct "d" ⟼ 1×1 struct
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
error
But we can still get the values in a cell array
values(d,"cell")
ans = 4×1 cell array
{1×1 struct} {1×1 struct} {1×1 struct} {1×1 struct}
Guido Hiller
Guido Hiller on 9 Dec 2022
@Paul Thank you for your answer. I think I had a misunderstanding about the behaviour of structs. If you can put structs with different fields into the same dictionary, then my inital question does not make any sense.

Sign in to comment.

Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!