How to create an empty dictionary with a struct as value
Show older comments
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 Comments
Jan
on 8 Dec 2022
What do you expect struct(test={}) to do? Why do you think, that this creates a struct called "test"?
Guido Hiller
on 8 Dec 2022
@Jan, As you can see below, it actually does something, as this is using the Name=Value syntax. So it is equivalent to the second call:
str = struct(test={})
str = struct('test',{})
@Rik: Thanks. I ran the same code struct(test={}) yesterday here in the forum and got an error message. Strange.
@Guido Hiller: Thanks for your explanation. What is the meaning of assining an empty string in a dictionary? What about considering as a bug, that the dictionary command acceptes an empty value for an empty key? Would stopping with an error message be better?
Or in other words: Is an empty dictionary meaningful? I know, there are empty structs with fields, so maybe the answer is "yes".
Guido Hiller
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)
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")
Guido Hiller
on 9 Dec 2022
Answers (0)
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!