Keep variable in the memory without declaring it as global

조회 수: 3 (최근 30일)
CaG
CaG 2021년 2월 9일
답변: Steven Lord 2021년 2월 11일
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
Rik
Rik 2021년 2월 11일
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?

댓글을 달려면 로그인하십시오.

답변 (2개)

darova
darova 2021년 2월 11일
편집: darova 2021년 2월 11일
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
CaG
CaG 2021년 2월 11일
편집: CaG 2021년 2월 11일
Good point. It's the same reason why I cannot give directly y to the second function. Thus, it is not a viable option.

댓글을 달려면 로그인하십시오.


Steven Lord
Steven Lord 2021년 2월 11일
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?

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by