MATLAB: How do you index an array inside an array of structures

array inside structurearray of structuresindexing structures

I would like to index an array which is one of the fields of an array of structures. For example if I have something like:
s(1).field = [1 2 3 4];
s(2).field = [2 4 6 8];
I would like to access all of the 2nd values of s.field. However something like [s.field(2)] gives the error "Expected one output from a curly brace or dot indexing expression, but there were 2 results." I know there are other ways to structure this data but I'm just constructing the simplest example possible (my real application has other fields which are not arrays and a much larger number of entries). With a structure in this format I know I could call [s.field] and reshape it and index but that's a bit hard to read. My current solution is to loop through all the entries but I feel like there must be a better solution.

Best Answer

There is no direct method for "nested indexing". Your loop method is the best way, if you pre-allocate the output.
This is a disadvantage of the chosen structure. Using a different method to store the values might be more convenient. Sometimes this can be seen, when the program is in its final state when the bottlenecks are optimized. Therefore it is a smart strategy to write the code as independent as possible from the underlying structure of the data, such that it can be adjusted later without the need to rewrite the complete code.
len = size(s, 1);
v = zeros(len, 1);
for kk = 1:len
v(kk) = s(kk).field(2);
end