MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

If all of the fields contain the same type of data and can form a hyperrectangle, you can
concatenate the list items. For example, create a structure nums with scalar numeric
values in field f, and concatenate the data from the fields:


nums(1).f = 1;
nums(2).f = 2;
nums(3).f = 3;


allNums = [nums.f]


This code returns


allNums =
1 2 3


If you want to process each element of an array with the same operation, use the
arrayfun function. For example, count the number of elements in field f of each struct
in array s:


numElements = arrayfun(@(x) numel(x.f), s)


The syntax @(x) creates an anonymous function. This code calls the numel function for
each element of array s, such as numel(s(1).f), and returns


numElements =
1 3 9


For related information, see:



  • “Comma-Separated Lists” on page 2-78

  • “Anonymous Functions” on page 20-24


Access Elements of a Nonscalar Struct Array
Free download pdf