Container with array as values

4 vues (au cours des 30 derniers jours)
Daniele Notarmuzi
Daniele Notarmuzi le 9 Fév 2021
I need to build something like a python dictionary. I need to fill it dynamically, using numbers as keys and arrays as values. Specifically:
  • I will want the object to be of the form
MyObj(1) = [1,2,3,4]
MyObj(2) = [10,20,30,40]
...
MyObj(n) = [val1, val2, val3, val4]
  • I need it to be filled dynamically. I have two for loops. For each value of the outter loop, I declare an array and fill in the inner loop. At the end of this loop, I need to use the array as the value of MyObj.
I (think I) have managed to deal with the keys: for example I would do
keySet = ['1','2','3','4']
MyObj = containers.Map('KeyType','char','ValueType','?????????????');
for i=1:4
TheArrayToFill = [];
% Inner loop for j=1:50. Fill the array as TheArrayToFill(j) = SomeNumber
MyObj(keySet(i)) = TheArrayToFill % How can I make this work?
end
The idea is that, at the end, I get an object with 4 keys, with each key having a 50-cells numeric array as values. How can I accomplish this?
Note: I'm new to Matlab. I am using a container as it seemed the proper datastructure. If there is a better datastructure, I'll gladly switch to it. In this latter case, an example would be great.

Réponse acceptée

Daniele Notarmuzi
Daniele Notarmuzi le 9 Fév 2021
Ok, It seems I can use This answer to make the trick.
  • Declare the container without specifiying the key-value types;
  • Use the index of the outter loop as key. It needs to be converted to a string
  • In this way I can use the array as a value
MyObj = containers.Map();
for i=1:4
TheArrayToFill = [];
% Inner loop for j=1:50. Fill the array as TheArrayToFill(j) = SomeNumber
MyObj(int2str(i)) = TheArrayToFill % How can I make this work?
end

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Produits


Version

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by