Container with array as values

4 次查看(过去 30 天)
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.

采纳的回答

Daniele Notarmuzi
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by