Container with array as values

조회 수: 10 (최근 30일)
Daniele Notarmuzi
Daniele Notarmuzi 2021년 2월 9일
답변: Daniele Notarmuzi 2021년 2월 9일
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
Daniele Notarmuzi 2021년 2월 9일
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