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

Mukul Khandelwal さんによって質問されました 2015 年 12 月 20 日
最新アクティビティ Stephen Cobeldick
さんによって 編集されました 2015 年 12 月 21 日
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 件のコメント

サインイン to comment.

タグ

2 件の回答

回答者: 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!

  0 件のコメント

サインイン to comment.


回答者: 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.

  0 件のコメント

サインイン to comment.



Translated by