为结构体数组生成代码
此示例说明如何编写使用结构体数组的 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).y = 20; 代码生成不支持这种“动态”样式的结构体构建。其中一个原因是,在 MATLAB 中,一个结构体数组的两个不同元素可能有不同结构体字段,这与更为静态的类型推断方法相冲突。因此,您需要首先完全指定基本标量元素,然后从这个完全指定的元素扩展为一个结构体数组。此方法可以保证结构体数组的两个元素始终具有相同的类型(字段)。
生成 MEX 函数
使用命令 codegen
后跟要编译的 MATLAB 文件的名称,生成一个 MEX 函数。
codegen struct_array
Code generation successful.
默认情况下,codegen
在当前文件夹中生成名为 struct_array_mex
的 MEX 函数。这允许您测试 MATLAB 代码和 MEX 函数,并将结果进行比较。
运行 MEX 函数
struct_array_mex(10)
ans=1×10 struct array with fields:
x
y
vx
vy