从单元格数组中删除一些行并创建一个新的单元格数组

时间:2016-12-20 05:59:48

标签: arrays matlab cell-array

我想删除包含字符串(mx1)的单元格Pen Drive和空单元格[]

例如:如果我有一个单元格数组:

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'}

然后新的单元格数组必须包含:

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

2 个答案:

答案 0 :(得分:3)

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'))) = [];

如果您有R2016b,那么有一个新函数contains,它返回一个逻辑值,表示字符串中存在匹配项,因此删除具有指定字符串的行可以写为

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

为了便于阅读,这比非空的测试的双重否定更容易。

答案 1 :(得分:0)

在这里找到许多可能的解决方案之一。我已经使用for循环来检查每个字符串是否为空或者搜索到的令牌在里面:

toDelete = [];
for i=1:length(S_Block)
    % check for the string if it's empty
    if isempty(S_Block{i})
        % store the index of the string
        toDelete = [toDelete i];
        continue;
    end;
    % search for the token 'Pen Drive'
    if ~isempty(strfind(S_Block{i},'Pen Drive'))
        % store the index of the string
        toDelete = [toDelete i];
    end;
end;

% delete all found strings from the cell-array
S_Block(toDelete) = [];