Sevenless
Sevenless

Reputation: 2835

How to clear a persistent variable in a MATLAB method

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.

Upvotes: 1

Views: 2643

Answers (2)

German Gomez-Herrero
German Gomez-Herrero

Reputation: 533

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.

Upvotes: 4

Amro
Amro

Reputation: 124563

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

Upvotes: 4

Related Questions