mlock not working, variables getting cleared in function switch.

조회 수: 5 (최근 30일)
as
as 2020년 8월 25일
댓글: Jan 2020년 8월 30일
M using Multiple function in a single '.m' file.
when i make a function call the previous data of the calling function is getting cleared.
Even if i use mlock then also data is getting cleared from in between function calls.
Is there any other method i can preserve variable and data of my main function.
  댓글 수: 2
Geoff Hayes
Geoff Hayes 2020년 8월 25일
as - how are you storing the previous data? Is this data the output from calling this function before? Can you provide an example that demonstrates this problem?
as
as 2020년 8월 26일
편집: as 2020년 8월 26일
function add(a,b)
mlock
c= a+b
d = subtract(a,b)
end
function k = subtract(e,f)
k = e-f;
end
Thank you Geoff Hayes .In above code when program reaches at ->k=e-f , variable c get destroyed even though i used mlock. If this is not correct use of mlock then please provide an example. What i want is to preserve variable c till the end of execution of function add() and in between call other function too.
In my script i'am loading a ROM.m file with lots of variable in it which i will be using in simulation, but when i call another function workspace is getting cleared.

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

답변 (1개)

Jan
Jan 2020년 8월 25일
편집: Jan 2020년 8월 25일
Create this file:
function demo(In)
persistent v
switch lower(In)
case 'lock'
mlock
disp('locked')
case 'unlock'
munlock
disp('unlocked')
case 'set'
v = rand
case 'show'
v
end
end
Now run it:
demo('show') % v is []
demo('set')
clear('demo') % v is cleared
demo('show') % v is []
demo('set') % v is set to a value
demo('show') % v keeps its value
demo('lock')
clear('demo') % v is not cleared
demo('show') % v kept its value
demo('unlock')
clear('demo') % v is cleared
demo('show') % v is [] again
So usually declaring a variable as persistent is sufficient already and you need mlock only, if a brute program calls clear all (which is a bad programming pattern!).
  댓글 수: 2
as
as 2020년 8월 26일
Thank you Jan, but here am loading a complete ROM file with lots of variable and their value, so i need to preserve that workspace for my entire run of that function and also call other function in between. Is it possible to load that ROM.m file as persistent?
Jan
Jan 2020년 8월 30일
Of course the workspaces are cleared,when a function is left, except if a variable is stored persistently. So just import the "ROM file" (what ever this means) into a variable, which is declared as persistent.

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

카테고리

Help CenterFile Exchange에서 Scope Variables and Generate Names에 대해 자세히 알아보기

제품


릴리스

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by