2
votes

I have a class with a persistent variable in a static method. For testing purposes, I would like to clear it. The Matlab documentation for clear states:

To clear a particular class, use clear myClass.

And that direction is given in How to clear a persistent variable in a MATLAB method

However, that hasn't worked for me. Here is a simple example of the issue. When the method is called with a single argument, that argument is assumed to be a matrix to be stored in the persistent variable. When the function is called with two arguments, those are assumed to be index references into the stored matrix.

The class def file, exampleClass2.m, located in directory @exampleClass2

classdef exampleClass2
    methods (Static=true)
        out = foo(varargin)
    end
end

foo.m, located in directory @exampleClass2

function out = foo(varargin)
    persistent persistMat;
    switch nargin
        case 1
            assert (ndims(varargin{1}) == 2)
            persistMat = varargin{1};
        case 2
            out = persistMat(varargin{1},varargin{2});
    end
end

and a test script

exampleClass2.foo(magic(5));
exampleClass2.foo(2,3)

ans = 7

clear exampleClass2
exampleClass2.foo(2,3)

ans = 7

What should I do to clear this persistent variable, and why doesn't clearing the class also clear the persistent variable?

1
A trivial answer to your question would be exampleClass2.foo([]). :) - Cris Luengo

1 Answers

2
votes

Why Clearing the Class Name Didn't Work

The reason the usual clear className didn't clear the persistent variable is because the method was defined in a different .m file, as demonstrated when the method definition in included in the class def file.

classdef exampleClass3
    methods (Static=true)
        function out = foo(varargin)
            persistent persistMat;
            switch nargin
                case 1
                    assert (ndims(varargin{1}) == 2)
                    persistMat = varargin{1};
                case 2
                    out = persistMat(varargin{1},varargin{2});
            end
        end
    end
end

Now test it

exampleClass3.foo(magic(5));
exampleClass3.foo(2,3)

ans = 7

clear exampleClass3
exampleClass3.foo(2,3)

Index exceeds matrix dimensions.

How to Clear When Method In Separate .m File

To clear the persistent variable of the static method when the method is defined in a separate .m file, use clear methodName. For example, using the definitions from the question:

exampleClass2.foo(magic(5));
exampleClass2.foo(2,3)

ans = 7

clear foo
exampleClass2.foo(2,3)

Index exceeds matrix dimensions.

What if the path includes a separate function foo, or other classes exist with a foo method?

Unfortunately, clear exampleClass2.foo does not work:

exampleClass2.foo(magic(5))
clear exampleClass2.foo
exampleClass2.foo(2,3)

ans = 7

So if the path includes a function foo, or other classes have a foo method, the persistent variables of all such functions/methods will be cleared.