Работа с массивами структур

В этом примере показано, как записать функцию MATLAB, которая использует массивы структур так, чтобы это подошло для генерации кода. Для генерации кода необходимо сначала создать скалярную версию шаблона структуры прежде, чем вырастить его в массив. Механизм логического вывода генерации кода использует тип этого скалярного значения как базовый тип массива.

Необходимые условия

Нет никаких необходимых условий для этого примера.

О struct_array Функция

struct_array.m файл использует массив структур.

type struct_array
% 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;

В MATLAB, при создании массива структур, вы обычно только добавляли бы поля, когда вы идете. Например, s (1).x = 10; s (2) год = 20; Этот "динамический" стиль конструкций здания не поддерживается для генерации кода. Одна причина состоит в том, что возможно в MATLAB иметь поля отличной структуры для двух различных элементов массива структур, который конфликтует с более статическим подходом вывода типа. Поэтому необходимо полностью указать основной скалярный элемент сначала, и затем вырастить массив структур от этого полностью указанного элемента. Этот метод гарантирует, что два элемента массива структур всегда совместно используют тот же тип (поля).

Сгенерируйте MEX-функцию

Сгенерируйте MEX-функцию с помощью команды codegen сопровождаемый под названием файл MATLAB, чтобы скомпилировать.

codegen struct_array

По умолчанию, codegen генерирует MEX-функцию под названием struct_array_mex в текущей папке. Это позволяет вам тестировать код MATLAB и MEX-функцию и сравнивать результаты.

Запустите MEX-функцию

struct_array_mex(10)
ans=1×10 struct array with fields:
    x
    y
    vx
    vy

Для просмотра документации необходимо авторизоваться на сайте