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

35 views (last 30 days)
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?

Answers (1)

Philippe Lebel
Philippe Lebel on 15 Jan 2020
Edited: Philippe Lebel on 15 Jan 2020
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:

Categories

Find more on Scope Variables and Generate Names 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!