Global variables between Base Workspace and Simulink in MATLAB

1.3k Views Asked by At

I'm currently struggling to achieve proper global communication between the variables in the base workspace of MATLAB (created by a init.m script), and some functions that are used in some Function Blocks in my Simulink scheme. The idea behind the use of these global variables is to initialize them in the init.m file, run the execution and the simulation, and then if I want to change some parameters, I just change them in that script. I've tried different things, but they don't seem to work

  • I've tried to use the Data Store Memory block, but if I've understood right, they only achieve globality within Simulink functions, and not between Simulink and Base Workspace;
  • I've also tried with some Simulink.Signal classes, but either I didn't use them right or they didn't work.

The ultimate behaviour I want to achieve should be something like this:

In the init.m file

global g0 k Kp Kd;
g0 = 9.81;
k = 0;
Kp = diag([1/3,1/3]);
Kd = diag([1/3,1/3]);

and then in any Simulink function I want to use I'll just do the following:

global Kp;
global Kd;
ddr = ddr_des + Kd*(dr_des - dr) + Kp*(r_des - r);

EDIT: more explanations on what I've tried. As I said, I've tried to work with Data Store Memory blocks in Simulink to try to achieve globality, and the way I did it is the following.

  1. I initialized global variables in the init.m file like I wrote before
  2. I recall the variables in the Function Block by writing global + their name.
  3. In the Simulink scheme, I add the Data Store Memory blocks Simulink blocks
  4. Then, in the Edit Data section of the Function Blocks I modify the scope of those global variables into the Data Store Memory scope

I'm sure that this approach doesn't work because, when I hard-code the values of the variables in the function (instead of using the global variables) and I simulate everything, I get some results, while instead if I try to execute with that approach I get several errors that I've understood they're related to not seeing any data in the global variables.

Regarding the Simulink.Signal thing, I don't really remember the various things I tried with them, so if anyone thinks it's the proper way to do it please let me know.

0

There are 0 best solutions below