How to declare variables immune to clear all?

前端 未结 3 1385
没有蜡笔的小新
没有蜡笔的小新 2020-12-11 16:44

Is there anyway to declare variables immune to clear all in MatLab? One solution I thought of was saving the variables and reopening them whenever I need them. Can anyone th

3条回答
  •  悲&欢浪女
    2020-12-11 17:10

    First of all, you should use local variables wherever possible. If someone clears the base workspace it does not matter for these variables:

    function yourcode()
    x=1
    evilblackbox()
    %x is still here
    disp(x)
    end
    
    
    function evilblackbox()
    clear all
    end
    

    There is a ugly workaround, but I really recommend not to use it. You will end up with code which requires restarting matlab whenever you exit the debugger at a wrong location, it throws an exception or similar stupid stuff.

    function r=crcontainer(field,data)
    persistent X
    mlock
    if exist('data','var')
        X.(field)=data;
    end
    r=X.(field);
    end
    

    To put a variable in it, use crcontainer('name',3), to read it use crcontainer('name')

提交回复
热议问题