How to run a m file in a function which is called in another m file?
3 views (last 30 days)
Show older comments
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 Comments
Stephen23
on 9 May 2017
Edited: Stephen23
on 9 May 2017
"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
on 9 May 2017
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.
Answers (1)
Walter Roberson
on 9 May 2017
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 Comments
See Also
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!