Create an Array of different Size Structs that have the same information

조회 수: 26 (최근 30일)
Angel Garcia
Angel Garcia 2021년 11월 17일
답변: Mrinal Anand 2023년 7월 13일
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)

답변 (1개)

Mrinal Anand
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!

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by