%% Working with Structure Arrays
% This example shows how to write a MATLAB function that uses structure arrays so that it is suitable for code generation. For code generation, you must first create a scalar template version of the structure before growing it into an array. The code generation inference engine uses the type of this scalar value as the base type of the array.
%% Prerequisites
% There are no prerequisites for this example.
%% About the struct_array Function
% The struct_array.m file uses a structure array.

type struct_array

% In MATLAB, when building up a structure array, you would typically just add fields as you go. For example, s(1).x = 10; s(2).y = 20; This "dynamic" style of building structures is not supported for code generation. One reason is that it is possible in MATLAB to have different structure fields for two different elements of a structure array, which conflicts with the more static approach of type inference. Therefore, you need to fully specify the base scalar element first, and then grow a structure array from this fully specified element. This method guarantees that two elements of a structure array always share the same type (fields).
%
%% Generate the MEX Function
% Generate a MEX function using the command codegen followed by the name of the MATLAB file to compile.

codegen struct_array

% By default, codegen generates a MEX function named struct_array_mex in the current folder. This allows you to test the MATLAB code and MEX function and compare the results.
%
%% Run the MEX Function

struct_array_mex(10)

% Copyright 2018 The MathWorks, Inc.