codegen: can I use a Matlab global structure in a mex function created with codegen?

2 visualizaciones (últimos 30 días)
I have a global structure S defined in my Matlab function and I use it in another function I want to compile with coder. Is it possible? How can I tell the coder that S is a Matlab structure? Example:
File function_1.m:
function_1
global S
S = struct ('a', 0);
File function_2.m:
function_2 %#codegen
global S
x = S.a + 2;
If I compile function_2.m the coder notify an error; how can I do?

Respuesta aceptada

Fred Smith
Fred Smith el 21 de Nov. de 2012
MATLAB globals are tricky.. There is a single global workspace containing all of your MATLAB global variables. You bind a name to the global workspace using:
global g;
This accesses an existing global g or creates a new global g containing an empty matrix.
The codegen command will use the value of your MATLAB global to guess a type for the global variable. By default generated MEX-functions pick up the global values from MATLAB so that it behaves just like your MATLAB code. In standalone code generation, the global will start with the value it had when you issued the codegen command.
You can define a global in MATLAB at the command line as follows:
>> global g;
>> g = struct('a',0);
After this codegen should infer the type from this definition and will start with the same initial value as MATLAB.
Alternatively, you can use the -global option to the codegen command to override the type, and optionally the initial value of the global. You need to specify the type if you want the global to be variable-sized. This is done in the same way as the -args specification for inputs.
Hope that helps,
Fred

Más respuestas (1)

Kaustubha Govind
Kaustubha Govind el 19 de Nov. de 2012
I wonder if you should do something like:
function_2 %#codegen
global S
if isempty(S)
S = struct ('a', 0);
end
x = S.a + 2;
  2 comentarios
Giuela
Giuela el 19 de Nov. de 2012
Doesn't work, the error message for the line #4 ("if isempty(S)") is:
Could not find initial value for global variable 'S'
Kaustubha Govind
Kaustubha Govind el 19 de Nov. de 2012
Is 'S' defined in the MATLAB workspace at this point? It looks like your original definition should have worked according to Generate C Code from Code Containing Global Data

Iniciar sesión para comentar.

Categorías

Más información sobre Generating Code en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by