Create an Array of different Size Structs that have the same information
26 次查看(过去 30 天)
显示 更早的评论
I am Trying to create either a struct or an array that has a struct nested within but do not know how to go about it. More Specifically I want the outermost struture to be "Week n" where n is an inputed value (1:10) . Within this I would like to store a structures of the same information. An analogy would be if I had a form with a FirstName, LastName, PhoneNumber (all 1 struct) and I put 3 forms in filecabinet 1; 4 in filecabinet 2; and 8 in filecabinet 3.
%This would be an example of One struct, the categories will remain the
%same but the # of contents will change for each week
People = struct('First', {'Alpha','Beta','Charlie'},...
'Last',{'Miller','Douglas','Doe'},...
'Number',{123 , 345, 789})
num = [3,4,8];
%num is the number of structs of People and NOT the index
%Week 1:3 would be an example of wanting a total of 3 larger categories
Week(1:3) = People (num)
0 个评论
回答(1 个)
Mrinal Anand
2023-7-13
You can create a struct of structs and use loops to access the inner structs' fields. Here is an example using the code sample that you have provided:
num = [3, 4, 8];
num_weeks = length(num);
Week = struct(); % Initialize the outermost structure
for n = 1:num_weeks
% Create the nested structures for each week
People = struct('FirstName', {}, 'LastName', {}, 'PhoneNumber', {});
% Add the specified number of People structures to the current week
for i = 1:num(n)
People(i).FirstName = '';
People(i).LastName = '';
People(i).PhoneNumber = '';
end
% Add the nested People structure to the current week in the outermost structure
Week(n).People = People;
end
This can get you the desired result. Hope it helps!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!