How to clear a persistent variable in a MATLAB method

限于喜欢 提交于 2019-12-11 12:44:48

问题


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 clear functions which has excessively broad scope for my purposes.

The classdef .m file for this problem:

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

A script that employs this class:

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

The output from this is:

>> 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

which is the desired output. The problem is that the line clear functions in the classdef file clears all functions in memory. I need a way to clear with a much smaller scope. For example, if hasPersistent' was a function instead of a method, the appropriately scoped clear statement would beclear hasPersistent`.

I know that clear obj.hasPersistent and clear testMe.hasPersistent both fail to clear the persistent variable. clear obj is similarly a bad idea.


回答1:


Following the discussion in the comments, I think you want to use make foo a private property, accompanied with appropriate increment/reset public functions.




回答2:


You definitely don't need a persistent variable to implement what you want. But, in any case, to remove a persistent variable from a class method you have to clear the corresponding class. In your case, clear testMe should do what you want.

A related issue is how to clear a persistent variable in a package function. To remove persistent variable myVar from function foo within package foo_pkg you have to do this:

clear +foo_pkg/foo

This should work as long as the parent folder of folder +foo_pkg is in the MATLAB path.



来源:https://stackoverflow.com/questions/10777924/how-to-clear-a-persistent-variable-in-a-matlab-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!