How to create global variables in MATLAB Python workspace
16 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Consider the following case:
A main python file calls three different MATLAB functions -- func_initialize.m, func_1.m and func_2.m.
func_initialize take some arguments from the Python workspace, and creates a list of global variables: aa, bb and cc. These variables are then used in func_1 and func_2.
func_initialize is structured as follows:
function func_initialize(args)
% Do some calculations using args
global aa bb cc
% Set values of aa bb and cc
end
However, within the python script, when I call these functions from the workspace dictionary:
import matlab.engine
eng = matlab.engine.start_matlab()
eng.workspace['aa']
it gives me the following error:
MatlabExecutionError:
File /usr/local/MATLAB/R2019a/toolbox/matlab/external/engines/engine_api/+matlab/+internal/+engine/getVariable.m, line 27, in getVariable
Undefined variable 'aa'.
What's wrong with the programming logic? Could there be a better way to share data between the three MATLAB files?
In my actual code, a Python object has some methods which call these three MATLAB functions. MATLAB engine is started by the class constructor. Then the class methods use this MATLAB engine to call various functions and access the variable names.
2 commentaires
Rik
le 2 Oct 2019
You need to declare global variables in every workspace. So if you set it in a function, it won't be in your main workspace.
Also, globals are a bad idea and you almost never need them.
Réponses (1)
Shrinidhi KR
le 7 Mai 2020
You can use a getter function instead of accessing the variables as eng.workspace['aa'].
function aa = getvals()
global aa
end
In python script use the getter function to fetch the value of global variable:
import matlab.engine
eng = matlab.engine.start_matlab()
eng.func_initialize(1,2,3, nargout=0)
tf = eng.getvals()
print(tf)
A getter function like this can return the value of global variable set elsewhere in any other function, i.e in your case func_initialize.
The point to note is that when accessing the global variable inside any other functions they still need to be declared as "global same_variable_name" first (as shown above in 'getvals' function), which references to the same set of global variables and hence can access their values across.
The documentation also provides a similar setter and getter approach while sharing global varibales across functions in Matlab: https://www.mathworks.com/help/matlab/ref/global.html
1 commentaire
Rik
le 7 Mai 2020
I would strongly encourage you to use much longer names for your global variable to avoid name collisions.
Voir également
Catégories
En savoir plus sur Call MATLAB from Python dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!