How to run a m file in a function which is called in another m file?
1 回表示 (過去 30 日間)
古いコメントを表示
I want to Load variables taken from a user in a function.
I could think of two ways.
1) I created a m file to take user input ( So I have 3 files- Main m file, Function, Input m file)
Now I wanted to run that Input m file in a function which is called in the main m file.
How could I load workspace variables from that input m file into the function.
2) To take input in The main m file ( I have 2 files- Main m file, Function)
Now I want to load all the variables in workspace in that called function
As there are many variables in workspace (approx 20) which are required in the function, Is there any short cut to load all the workspace variables in that function?
2 件のコメント
Stephen23
2017 年 5 月 9 日
編集済み: Stephen23
2017 年 5 月 9 日
"Is there any short cut to load all the workspace variables in that function?"
This is a very bad practice that totally defeats the purpose functions. Functions are supposed to have their own workspace which is not affected by the rest of the universe. A function encapsulates some function, with clearly specified input and output arguments. Trying to force all variables from one workspace to another is how to make awful spaghetti code that is impossible to debug. Keep your workspaces independent!
Think of the fucntion sin: do you know what internal variables it uses? Do you think that sin's behavior should change depending on what variables might be defined in the calling workspace? (hint: this would make it impossible to use, because its behavior would then be practically unpredictable.)
Summary: Read the documentation:
and note that it clearly states which of these methods is preferred, and which is the worst choice to use. Then write your functions to simply pass arguments (this is the preferred method).
Adam
2017 年 5 月 9 日
A function that requires 20 variables sounds like a badly defined function! If it is just an entry function to a full program then you can just wrap them all up in a struct if you really need to pass in so many inputs.
回答 (1 件)
Walter Roberson
2017 年 5 月 9 日
http://matlab.wikia.com/wiki/FAQ#How_can_I_share_data_between_callback_functions_in_my_GUI.28s.29.3F
"Is there any short cut to load all the workspace variables in that function?"
Yes, there is, but it is seldom a good idea.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Startup and Shutdown についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!