Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to clear a persistent variable in a MATLAB method
    text
    copied!<p>I have a MATLAB class that contains a method that employs a persistent variable. When certain conditions are met I need to clear the persistent variable without clearing the object to which the method belongs. I've been able to do this, but only by employing <code>clear functions</code> which has excessively broad scope for my purposes.</p> <p>The classdef .m file for this problem:</p> <pre><code>classdef testMe properties keepMe end methods function obj = hasPersistent(obj) persistent foo if isempty(foo) foo = 1; disp(['set foo: ' num2str(foo)]); return end foo = foo + 1; disp(['increment foo: ' num2str(foo)]); end function obj = resetFoo(obj) %%%%%%%%%%%%%%%%%%%%%%%%% % this is unacceptably broad clear functions %%%%%%%%%%%%%%%%%%%%%%%%% obj = obj.hasPersistent; end end end </code></pre> <p>A script that employs this class:</p> <pre><code>test = testMe(); test.keepMe = 'Don''t clear me bro'; test = test.hasPersistent; test = test.hasPersistent; test = test.hasPersistent; %% Need to clear the persistent variable foo without clearing test.keepMe test = test.resetFoo; %% test = test.hasPersistent; test </code></pre> <p>The output from this is:</p> <pre><code>&gt;&gt; testFooClear set foo: 1 increment foo: 2 increment foo: 3 increment foo: 4 set foo: 1 test = testMe Properties: keepMe: 'Don't clear me bro' Methods </code></pre> <p>which is the desired output. The problem is that the line <code>clear functions</code> in the classdef file clears all functions in memory. I need a way to clear with a much smaller scope. For example, if <code>hasPersistent' was a function instead of a method, the appropriately scoped clear statement would be</code>clear hasPersistent`.</p> <p>I know that <code>clear obj.hasPersistent</code> and <code>clear testMe.hasPersistent</code> both fail to clear the persistent variable. <code>clear obj</code> is similarly a bad idea.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload