How to set the function to be able to use all variables in the script without need to be named in the function def?

22 ビュー (過去 30 日間)
When defining the function at the end of script, I realized that if I want to use a variable in that function I shouls add it as input. e.g. assume a variable called a=2 in the script and when I write a function that uses a in its calculations I need to add a to the declaration of function like [b]=example_function(a). There are several varaibles in the script that are going to be used in the function and naming all of them in the declaration of function wont be efficient. Is there any way to avoid thsi?
  1 件のコメント
Stephen23
Stephen23 2020 年 1 月 15 日
編集済み: Stephen23 2020 年 1 月 15 日
Convert the script to a function, then use nested functions:
All of the methods of passing data between workspaces are explained here:
Avoid using global variables.

サインインしてコメントする。

回答 (1 件)

Philippe Lebel
Philippe Lebel 2020 年 1 月 15 日
編集済み: Philippe Lebel 2020 年 1 月 15 日
i would suggest creating a struct containing the required variables.
%my script
params.a = 1;
params.b = "very string"
params.c = [2,3,54];
result = my_func(params);
function result = my_func(params)
% my function
for i=1:length(params.c)
disp(params.b)
end
result = params.a;
end
There would also be declaring global variables.
i'd advice not to do that because it will come back to haunt you in future projects.
The goal of functions is to compute things in their own workspace and not affect other parts of the code with their local variables. You may quickly loose control of your code when assigning a lot of global variables and not being sure where they are interacted with.
In any case, if you are feeling lucky and want to try doing it with global variables, here is the doc:

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by