Keep variable in the memory without declaring it as global
5 views (last 30 days)
Show older comments
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
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?
Answers (2)
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?
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!