Create an Array of different Size Structs that have the same information
조회 수: 18 (최근 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!