automating global definition inside multiple functions

1 view (last 30 days)
A few nonlinear systems of equations are being processed by a few functions. Each function can change some or all of the variables. fsolve is used in each function. There are many variables. Is there an easy way to share (or pass) related variables in the main workspace among these functions? Name of variables are already stored as strings in a variable_register in the main workspace. Is there a command like the following that can be executed inside functions to automate the global definition:
for k=1:length(variable_register)
eval(['global variable_register{',num2str(k),'}'])
end
  2 Comments
Stephen23
Stephen23 on 2 May 2019
Do NOT do this.
Global variables make code slow, buggy, and very difficult to debug.
Dynamically accessing variable names forces beginners into writing slow, complex, obfuscated, buggy code which is hard to debug. Read this to know why:
And you want to combine these two counter-productive code practices together.... ouch.
Going down this path will hinder your code development. Rather than forcing yourself into writing bad code because of bad design decisions, just put those parameters into one structure or table or array. Then pass that as input/output arguments. Passing data as input/output arguments is the simplest and most effiicient way to pass data between workspaces.
S H
S H on 2 May 2019
I will surely use your advice and change my code. Thank you for sharing your experience.

Sign in to comment.

Answers (1)

James Tursa
James Tursa on 2 May 2019
Ugh! This is not a good code design. There are better choices. E.g., maybe use a struct with fields named for your variables, and then pass that single struct among your functions as an input/output argument.
  7 Comments
Stephen23
Stephen23 on 2 May 2019
Edited: Stephen23 on 2 May 2019
Using numbered variables, e.g.:
global A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15 A16 A17 A18 A19
is a sign that you are doing something wrong. Instead of awkwardly forcing meta-data (i.e. the index) into variable names (which makes acessing those variables slow and complex) you should use indexing. Indexing is neat, simple, and very efficient. Unlike what you atr trying to do.
Use cell arrays or structures or tables to pass your parameters.
Instead of using global variables to parameterize your functions, either use nested functions or anonymous functions:
Read the documentation carefully, ask us any questions... we will by happy to help you.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!