MATLAB Answers

S H
0

automating global definition inside multiple functions

S H
さんによって質問されました 2019 年 5 月 2 日
最新アクティビティ S H
さんによって コメントされました 2019 年 5 月 2 日
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 件のコメント

Stephen Cobeldick
2019 年 5 月 2 日
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
2019 年 5 月 2 日
I will surely use your advice and change my code. Thank you for sharing your experience.

サインイン to comment.

1 件の回答

James Tursa
回答者: James Tursa
2019 年 5 月 2 日

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 件のコメント

S H
2019 年 5 月 2 日
I have no prior experience with using struct in my codes. I could barely manage to understand and use cells recenly. Nothing beyond that.
Stephen Cobeldick
2019 年 5 月 2 日
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.
S H
2019 年 5 月 2 日
Thank you Stephen for sharing these links.

サインイン to comment.



Translated by