Best way to structure code with large matrices shared between multiple functions

11 visualizaciones (últimos 30 días)
I am trying to figure out the best way to structure my code, which uses large matrices that are used in multiple functions. The code must be compatible with Simulink Coder since it will be a MATLAB function block in Simulink and will eventually be converted to C.
I would basically like to have "global" variables to store the large matrices and have these matrices accessible from certain functions. These large matrices are constant. As an example, here's a few lines of C code that has the required behavior:
%%%data.c %%%
// This defines the (constant) global data
double mydata[3][1000] = {{3.5, 1.2, ...}, {2.1, 7.5, ...}, {7.4, 2.4, ...}};
%%%%%%%%%%%%%%
%%%functions.c %%%
// This brings in the global data so that functions within the "functions.c" file can use the mydata array
extern double mydata[3][1000];
%%%%%%%%%%%%%%%%%%%
What is the best way to recreate the above C code functionality in MATLAB?
I have a few ideas:
  • Just pass the large matrices in as an input to all the functions. This might work, but I am unsure how the memory gets handled. It would be very inefficient (or cause stack overflow issues) if the large matrices were copied because of the function call.
  • Use global variables. I am unfamiliar with using global variables within Simulink and Simulink Coder. Is this a good or bad idea?
Are there any other methods? Which is the best way to structure the code in terms of memory (or other relevant metrics such as ease of interfacing with the auto-generated C code)?
Thanks!

Respuestas (1)

Geoff
Geoff el 15 de Mzo. de 2012
MatLab is pretty clever about when to copy and when to pass by reference. Generally, a matrix passed as a parameter will only be copied once you change a value in it. Globals are strange in MatLab and I would avoid at all costs. Besides, a matrix with 3000 elements is not 'large'.

Categorías

Más información sobre Simulink Coder en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by