Search code examples
matlabsimulink

Delete all blocks except specified ones in simulink model


Is there any equivalent command to the clearvars -except keepVariables which can be used in a simulink model to delete all blocks, ports and lines, except specified ones?


Solution

  • This is one general way to do it, explained used the in-built example vdp:

    simulink;
    name = 'vdp';
    
    %// open system, pause just for displaying purposes
    open_system(name);
    % pause(3)
    
    %// find system, specify blocks to keep
    allblocks = find_system(name);
    ToKeep = {'Out1';'Out2'};
    %// add systemname to strings
    ToKeep = strcat(repmat({[name  '/']},numel(ToKeep),1), ToKeep);
    %// Alternative, directly, so save one line:
    ToKeep = {'vdp/Out1';'vdp/Out2'};
    
    %// create mask
    ToDelete = setdiff(allblocks,ToKeep);
    %// filter out main system
    ToDelete = setxor(ToDelete,name);
    
    %// try-catch inside loop as in this example not everything is deletable
    for ii = 1:numel(ToDelete)
        try
            delete_block(ToDelete{ii})
        catch 
            disp('Some objects couldn''t be deleted')
        end
    end
    

    If all objects are deletable you may use

    cellfun(@(x) delete_block(x),ToDelete)
    

    instead of the loop.


    Regarding your comment: Imagine you just want to keep all Scope and Out blocks. You need to find there names also by find_system and gather them to a list:

    %// what to keep
    scopes = find_system(name,'BlockType','Scope')
    outs = find_system(name,'BlockType','Outport')
    %// gather blocks to keep
    ToKeep = [scopes; outs];
    
    %// create mask
    ToDelete = setdiff(allblocks,ToKeep);
    %// filter out main system
    ToDelete = setxor(ToDelete,name);