MATLAB Answers

How do I share variables between files in a project?

5 views (last 30 days)
Sara Zimmo
Sara Zimmo on 14 Mar 2020
Answered: Jeff Miller on 14 Mar 2020
I have a very long code that I'd like to break it up into files.
I have a main file, called main.m
inside the main.m, I have
ini
calculation1
calculation2
report_plot
  • inside ini.m is all the variables to be initialized - and these values can change depending on the scenario.
  • inside calculation1.m is basically calculating using the variables initialized to create a traffic
  • inside calculation2.m is the heart of the program - does the simulation based on calculation1.m and ini.m
  • inside report_plot.m uses the results from the calculations2.m to report the results in a plot, may use ini.m
In reality, I have tons more files, which is why I'm asking for help in project management.
The issue here is that the variables are not being shared from one file to another. Not sure if creating a global variable is the best solution.

  2 Comments

Jacob Wood
Jacob Wood on 14 Mar 2020
What kind of variables do you have? Would it make sense to contain some of them in arrays, tables, or structures?
Utilizing functions wherever possible can help with project management.
Stephen Cobeldick
Stephen Cobeldick on 14 Mar 2020
"The issue here is that the variables are not being shared from one file to another."
You need to pass the variables as input/output arguments. Variables do not just jump from one workspace to another:
"Not sure if creating a global variable is the best solution."
In fact using global variables is about the second-worst solution.
The best solution, as the documentation explains, is to pass input/output arguments.

Sign in to comment.

Answers (1)

Jeff Miller
Jeff Miller on 14 Mar 2020
While not the best programming practice, a quick and dirty solution for your situation might be to return a "global-substitute" structure 'g' from ini and then pass g to all of the other routines, something like
g = ini;
calculation1(g)
calculation2(g)
report_plot(g)
The function ini could look like
funtion g = ini
g.var1 = 23;
g.othervar = 'string';
g.arrayvar = zeros(10,10);
to initialize whatever variables you want. Then your other functions can just refer to these variables with the g. prefix, such as
function calculation1(g)
x = sqrt(g.var1);
% and so on
end

  0 Comments

Sign in to comment.

Sign in to answer this question.