How to overload clarity

Overloading clear()with the function is simple. But how to access the workspace of an upstream function (from which it was called clear) to clear the workspace? builtin('clear')will clear only the workspace of the overloaded function.

function ret = someFun(a,b)
    ret = a + b;
    clear
    ret = 1;
end

function clear()
    persistent boring
    if isempty(boring), boring = 0; end
    boring = boring + 1;
    builtin('clear')
end

Screenshot: workspace of an upstream function after calling an overloaded function clear workspace of the upstream function after calling the overloaded clear function

+4
source share
1 answer

Use evalinwith option 'caller'. That is, replace the line

builtin('clear')

by

evalin('caller', 'builtin(''clear'')')

This will clear all variables from the workspace of the calling function.

If you want to remove all variables from the workspace of the Matlab base, use the parameter 'base':

evalin('base', 'builtin(''clear'')')
+4
source

All Articles