MATLAB: Looping over inputs provided by structure

inputsstructure

the Structure Setup
AppleDataGreen = struct('taste','Sour', 'color','Bright')
AppleDataRed = struct('taste','Sweet', 'color','Bright')
apples = struct( 'AppleType' ...
, struct('Green',struct(AppleDataGreen) ...
,'Red', struct(AppleDataRed)) )
I have a code that I want to run the data in the green structure and then run the Red structure
From matlab I was trying to us a for loop by doing this
% this takes me to the green and red structure giving me a
% length 2 hopefully
for i=1:length(apples.AppleType)
run(apples.AppleType{i})
code
end
error cell contents reference from a non-cell array object

Best Answer

The basic problem is that you are confusing the number of fields in a structure with the size of the structure. However these are two totally independent things: a structure is just like any other array: it can be empty, scalar, vector, etc. The number of fields it has is independent to its size. All of your structures are scalar, with various number of fields. Because your structures are scalar, it is not so interesting to check their size. What you actually want is to access the fields of the structure, something like this:
fn1 = fieldnames(apples.AppleType);
for k = 1:numel(fn1)
tmp = apples.AppleType.(fn1{k})
...
end
Better Alternative: storing the data in nested structures is confusing and complicated to access. I would recommend that you store your data in one simple non-scalar structure, without any nested structures at all:
S(1).name = 'Green';
S(1).taste = 'Sour';
S(1).color = 'Bright';
S(2).name = 'Red';
S(2).taste = 'Sweet';
S(2).color = 'Bright';
or equivalently by calling struct just once:
S = struct('name',{'Greeen','Red'}, 'taste',{'Sour','Sweet'}, 'color',{'Bright','Bright'})
Then it is trivial to access any apple/s using indexing, e.g. in a loop:
for k = 1:numel(S)
S(k)
end
Using a non-scalar structure really makes accessing your data easier, for example, to get all of the apples names in a cell array all you need is this:
>> {S.name}
Green
Red