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

8 次查看(过去 30 天)
I am having one variable x in one .m file and I want to use this variable (because I want that value in my other .m file) in other file.

回答(2 个)

Walter Roberson
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;
end
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
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.

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by