how to make global variable in matlab so that we can use in any .m file or any other method to use a variable in many .m files
조회 수: 14(최근 30일)
Walter Roberson 2015년 12월 20일
If the variable is intended to be read only, then the way to proceed is to make a .m file with the name of the variable that contains a function named after the variable that returns the appropriate value. For example,
function g_value = g
g_value = 9.81;
This can then be used in any .m or any method to obtain the value of the variable without needing to designate the value as being "global".
The more sophisticated version of this can be seen here
If the variable is not intended to be read only, then you can do something similar but creating "accessor functions" that read or write the value with the value internally being handled as global or something similar.
There is no method in MATLAB to just declare that a variable is to be shared without the other locations having to specifically say they want the shared version of it.
Imagine that you had an accounting package and someone came along and by adding a line of their own code in their own routine suddenly said "Mukul's bank account is shared everywhere. Now take $10000 from Mukul's bank account." So this is not a feature that you want in programming languages!
David Young 2015년 12월 20일
If the m-files are scripts, they share the same top-level workspace and you can access the same variables from both of them.
If one m-file is a function, or both are, then you can pass the value of x as an argument and return a value to x as a result.