Can MATLAB Handle a Triple Nested Struct?

1 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2020-10-22
编辑:Stephen23 2020-10-22
"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.

请先登录,再进行评论。

回答(2 个)

Jeff Miller
Jeff Miller 2020-10-21
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
Walter Roberson 2020-10-21
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.

类别

Help CenterFile Exchange 中查找有关 Calendar 的更多信息

标签

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by