Clean used variables while a functions is runing
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello,
I was wondering if there's any way to clean variables in function that are not used anymore later that function. For example:
function [out] = test(a,b)
c = a+b;
d = c+a;
out = d^2;
Here for example I want to clear 'b' after the first line and 'a' & 'c' after the sceond one.
Is there any automatic way to do so? I'm asking because I have very big matrices that I need to clean everytime and it will save me a lot of memory.
Thanks.
2 commentaires
Stephen23
le 25 Mar 2018
Modifié(e) : Stephen23
le 25 Mar 2018
"Is there any automatic way to do so? I'm asking because I have very big matrices that I need to clean everytime and it will save me a lot of memory.Is there any automatic way to do so? I'm asking because I have very big matrices that I need to clean everytime and it will save me a lot of memory."
I doubt that it will save you any memory. Your function changes neither a nor b, so MATLAB will not create copies of these in memory just for that function. As long as they both exist in the calling workspace there does not seem to be any benefit in clearing these variables.
For more information see:
John D'Errico
le 25 Mar 2018
Stephen's comment is a good answer. He should have answered this.
Neither a or b were changed there, so they are not copied until changes are made.
In fact, if you tried to clear a after it is used in line 1, I might even wager that might actually force a copy, for the clear to be then executed. So you might end up forcing MATLAB to temporarily use MORE memory (and time) than you are using now. This is something we could test, I suppose, with a function call, watching the memory usage carefully on some huge arrays.
So I did exactly that. if I do try to clear b and a, the code uses the same amount of memory. At least it does not try to allocate new memory for b.
In my test, the simple function, with no attempts to clear those variables internally, took slightly less time to run, but it took the same amount of memory, when compared to a version that tried to clear the variables.
So the clearing version saved no memory, but it did run more slowly.
Don't bother. Just buy more memory.
Réponses (1)
KALYAN ACHARJYA
le 25 Mar 2018
Modifié(e) : KALYAN ACHARJYA
le 25 Mar 2018
% you can use the clear variable
% First Call the function
c=test(a,b);
clear variables;
clear('test');
1 commentaire
John D'Errico
le 25 Mar 2018
Once you call test and it returns the answer, doing a clear will not help. Any variables temporarily created inside test were already deleted when the function terminated.
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!