How to create an empty dictionary with a struct as value
42 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Paul
el 9 de Dic. de 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")
Respuestas (0)
Ver también
Categorías
Más información sobre Structures en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!