Keep variable in the memory without declaring it as global

8 views (last 30 days)
I have a function that creates/loads a variable. This variable has to be later used in another (separated) function. However, in order to fulfill the software requirements, I cannot pass this variable as an input.
In order to solve this problem, I was thinking to use global variables. However, I'd like to avoid them for several reasons, especially because the runtime increases significantly. Thus I am seeking a way to do the following tasks
function func1(x)
global y
y = some_long_computation(x);
end
and
function w = func2(z)
global y
w = some_other_stuff(y, z);
end
without using global variables.
Is there a way to do so?
PS: If a mexable solution exists, it will be a huge plus.
  1 Comment
Rik
Rik on 11 Feb 2021
I don't understand your restrictions, so I'm not if this would help: would setting a preference work? Or setting a persistent variable in a wrapper function?

Sign in to comment.

Answers (2)

darova
darova on 11 Feb 2021
Edited: darova on 11 Feb 2021
Why can't you do something like
function y = func1(x)
y = some_long_computation(x);
end
function w = func2(x,z)
y = func1(x);
w = some_other_stuff(y, z);
end
  1 Comment
CaG
CaG on 11 Feb 2021
Edited: CaG on 11 Feb 2021
Good point. It's the same reason why I cannot give directly y to the second function. Thus, it is not a viable option.

Sign in to comment.


Steven Lord
Steven Lord on 11 Feb 2021
I have a function that creates/loads a variable. This variable has to be later used in another (separated) function. However, in order to fulfill the software requirements, I cannot pass this variable as an input.
Those seem like some bad requirements. "You need the data to do your job, but I can't give you the data."
If that requirement is related to you using your "another (separated) function" as the ODE function for a call to ode45 or as the objective for a call to fmincon or the like, see this documentation page that discusses parameterizing functions.
If you must do this, nesting the another function inside the function that loads the variable, or making them both methods of a class where you can store the loaded data as a property and access it from the object instance that's passed into the another function, or storing the data somehow inside one of the inputs the another function can accept under the requirements (the UserData property of a Handle Graphics handle, for instance) may be potential solutions. If there are other requirements that might disqualify our suggestions, can you share those requirements with us so we can take them into consideration?

Community Treasure Hunt

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

Start Hunting!