automating global definition inside multiple functions
조회 수: 1 (최근 30일)
이전 댓글 표시
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
Stephen23
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.
답변 (1개)
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
Stephen23
2019년 5월 2일
편집: Stephen23
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Surrogate Optimization에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!