MATLAB Answers

0

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

Asked by Mukul Khandelwal on 20 Dec 2015
Latest activity Edited by Stephen Cobeldick on 21 Dec 2015
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.

  0 Comments

Sign in to comment.

Tags

2 Answers

Answer by Walter Roberson
on 20 Dec 2015

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!

  0 Comments

Sign in to comment.


Answer by David Young
on 20 Dec 2015

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.

  0 Comments

Sign in to comment.