% y = struct_array(n)
% Take an input scalar number 'n' which will designate the size of the
% structure array return.
function y = struct_array(n) %#codegen

% Copyright 2010-2013 The MathWorks, Inc.

assert(isa(n,'double')); % Input is scalar double

% To create a structure array you start to define the base scalar element
% first. Typically, we initialize all the fields with "dummy" (or zero)
% values so the type/shape of all its contents are well defined.
s.x = 0;
s.y = 0;
s.vx = 0;
s.vy = 0;

% To create a structure array of fixed size you can do this in multiple
% ways. One example is to use the library function 'repmat' which takes a
% scalar element and repeats it to its desired size.
arr1 = repmat(s, 3, 5); % Creates a 3x5 matrix of structure 's'

% At this point you can now modify the fields of this structure array.
arr1(2,3).x = 10;
arr1(2,3).y = 20;
arr1(2,4).x = 5;
arr1(2,4).y = 7;

% Another way of creating a structure array of fixed size is to use the
% concatenation operator.
arr2 = [s s s; s s s; s s s; s s s; s s s];

% If two variables agree on base type and shape you can copy one structure
% array to the other using standard assignment.
arr2 = arr1;

% To create a structure array of variable size with a known upper bound can
% be done in multiple ways as well. Again, we can use repmat for this, but
% this time we will add a constraint to the (non constant) input variable.
% This guarantees that the input 'n' of this function is less than or equal to 10.
assert(n <= 10);

% Create a row vector with at most 10 elements of structures based on 's'
arr3 = repmat(s, 1, n);

% Or we can use a for-loop with the concatenation operator. The compiler is
% unable to analyze that 'arr4' will be at most 10 elements big, so we
% add a hint on 'arr4' using coder.varsize. This will specify that the
% dimensions of 'arr4' is exactly one row with at most 10 columns. Look at
% the documentation for coder.varsize for further information.
coder.varsize('arr4', [1 10]);
arr4 = repmat(s, 1, 0);
for i = 1:n
arr4 = [arr4 s];
end

% Let the top-level function return 'arr4'.
y = arr4;