Azzera filtri
Azzera filtri

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

17 visualizzazioni (ultimi 30 giorni)
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'},...
'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)

Risposte (1)

Mrinal Anand
Mrinal Anand il 13 Lug 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 = '';
% Add the nested People structure to the current week in the outermost structure
Week(n).People = People;
This can get you the desired result. Hope it helps!


Scopri di più su Structures in Help Center e File Exchange




Community Treasure Hunt

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

Start Hunting!

Translated by