Search code examples
arraysmatlabcell-array

Remove some rows from the cell array and create a new cell array


I want to remove the cells (mx1) which contain the string Pen Drive and empty cells [].

For example: if I have a cell array:

S_Block = {            []
                       []
           'D\My Folder\Amazing\Pen Drive'
           'C\Go To\Where\Home'
           'H\I am\No Where\Hostel'
           'F\Somewhere\Appartment\Pen Drive'
           'Ram\North\Sky\Pen Drive'
           'L\South\Pole\Ice'
                       []
           'Go\East\Japan\Pen Drive'}

Then new cell array must contain:

Snew_Block = { 'C\Go To\Where\Home'
               'H\I am\No Where\Hostel'
               'L\South\Pole\Ice'  }

Solution

  • Snew_Block = S_Block;      
    % Removing empty contents
    Snew_Block(cellfun(@isempty,Snew_Block)) = [];
    % Removing the rows having the specified string
    Snew_Block(~cellfun(@isempty,strfind(Snew_Block,'Pen Drive'))) = [];
    

    If you have R2016b then there is a new function contains this returns a logical value for when there is a match in the string so removing the rows with a specified strings can be written as

    % Removing the rows having the specified string
    Snew_Block(contains(Snew_Block,'Pen Drive')) = []
    

    For readability this is easier than the double negative of testing for something being not empty.