Can MATLAB Handle a Triple Nested Struct?
1 view (last 30 days)
Show older comments
I am trying to create a Calendar struct where it has Month struct and within the Month struct there is a Day struct. So far I have been able to get the Month struct to work within the Calendar struct :
Calendar = {};
Calendar.year = int8.empty;
Calendar.Month = {};
for i = 1:length(SIData)
Calendar(i).year = SIData(i).year;
Calendar(i).Month(1).month = 'January';
Calendar(i).Month(2).month = 'February';
Calendar(i).Month(3).month = 'March';
Calendar(i).Month(4).month = 'April';
Calendar(i).Month(5).month = 'May';
Calendar(i).Month(6).month = 'June';
Calendar(i).Month(7).month = 'July';
Calendar(i).Month(8).month = 'August';
Calendar(i).Month(9).month = 'September';
Calendar(i).Month(10).month = 'October';
Calendar(i).Month(11).month = 'November';
Calendar(i).Month(12).month = 'December';
end
However I cannot get the Day struct to go into the Month struct without throwing an error:
for i = 1:length(Calendar)
Calendar(i).Month.Day = {};
end
Error Message:
Scalar structure required for this assignment.
Error in Solar_Calc (line 32)
Calendar(i).Month.Day = {};
Any ideas to fix this problem would be greatly appreciated.
Thanks!
2 Comments
Stephen23
on 22 Oct 2020
Edited: Stephen23
on 22 Oct 2020
"Can MATLAB Handle a Triple Nested Struct?"
Yes.
Your data is very complex. Why are you assigning an empty cell array on one line:
Calendar = {};
and then replacing that and/or assigning lots of individual scalar structures? It appears that there is some confusion about data types: the best way to preallocate a structure is to use the struct command, and avoid
For such simple data your data design is ... complex. You should consider simplifying it.
Answers (2)
Jeff Miller
on 21 Oct 2020
Haven't tried it, but it seems like this should work:
for i = 1:length(Calendar)
for j=1:12
Calendar(i).Month(j).Day = {};
end
end
Walter Roberson
on 21 Oct 2020
Calendar = struct('Month', repmat({struct('month', '', 'Day', cell(31,1))},12,1), 'year', int8.empty);
The result is a 12 x 1 struct with fields Month and year. Each Month is a 31 x 1 struct with fields 'month' and 'Day'.
Might I suggest that this is not the structure that you want? There is no point in repeating month 31 times.
0 Comments
See Also
Categories
Find more on Calendar in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!