Effacer les filtres
Effacer les filtres

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

27 vues (au cours des 30 derniers jours)
Angel Garcia
Angel Garcia le 17 Nov 2021
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)

Réponses (1)

Mrinal Anand
Mrinal Anand le 13 Juil 2023
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!

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by