Brendan
Brendan

Reputation: 19353

How to get MATLAB to recognise newly added static methods?

I am using classes and static methods to 'scope' functions in a namespace, similar to C#. However, every time I add a new method to a class, at first it is not found. I have to restart the MATLAB environment (2007a) for the new methods to be recognised.

Surely there is an 'update' or 'refresh' type command that I can use so that I do not have to restart the MATLAB environment each time I add a function?

Upvotes: 5

Views: 2013

Answers (3)

William Payne
William Payne

Reputation: 3325

Clearing instances of your class should work.

Suppose that you have an instance of "MyClass" in your base workspace:

foo = MyClass;

Now, suppose you edit MyClass and add new static method "bar":

foo.bar(); % Will cause error, as foo is instance of previous "MyClass"

However, "clear"-ing foo will remove the reference to the previous class:

clear('foo');
foo = MyClass; 
foo.bar(); % this should now work.

This should be fine if you only have one or two instances of the class in your base workspace. If you have many instances of the class in your base workspace, then you may want to write a script to clear them:

varList = whos;
for iVar = 1:numel(varList)
    if isequal( 'MyClass', varList(iVar).class )
        clear( varlist(iVar).name );
    end
end
clear('varList');
clear('MyClass');

If you have instances of the class in more locations, you may wish to extend the script as appropriate.

The last call to clear the class name might only be necessary if you are making modifications to classes in an inheritance hierarchy.

Upvotes: 1

gnovice
gnovice

Reputation: 125854

Issuing this call to CLEAR should do it:

clear classes

One unfortunate side effect of this is that it also effectively issues a clear all, which clears all of the variables in the workspace as well (however, this would happen anyway when you close and restart MATLAB). This clearing of the workspace actually serves a purpose, since it will remove any variables of the same type as the old version of your class, which potentially wouldn't work correctly with the new version of your class.

The function REHASH may work, but I doubt it (I think it deals more with file paths than class definitions).

Upvotes: 6

Ashish Uthama
Ashish Uthama

Reputation: 1331

try "clear classname"

Upvotes: 0

Related Questions