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
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
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
Walter Roberson 2017-5-9

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by