Container with array as values

4 views (last 30 days)
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.

Accepted Answer

Daniele Notarmuzi
Daniele Notarmuzi on 9 Feb 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

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!