从元胞数组中删除一些行并创建一个新的元胞数组
Remove some rows from the cell array and create a new cell array
我想删除包含字符串 Pen Drive
的单元格 (mx1)
和空单元格 []
。
例如:如果我有一个元胞数组:
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' }
在这里找到许多可能的解决方案之一。我使用了一个 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) = [];
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
这个 returns 当字符串中有匹配时的逻辑值所以删除具有指定字符串的行可以写成
% Removing the rows having the specified string
Snew_Block(contains(Snew_Block,'Pen Drive')) = []
为了可读性,这比测试非空的双重否定更容易。
我想删除包含字符串 Pen Drive
的单元格 (mx1)
和空单元格 []
。
例如:如果我有一个元胞数组:
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' }
在这里找到许多可能的解决方案之一。我使用了一个 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) = [];
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
这个 returns 当字符串中有匹配时的逻辑值所以删除具有指定字符串的行可以写成
% Removing the rows having the specified string
Snew_Block(contains(Snew_Block,'Pen Drive')) = []
为了可读性,这比测试非空的双重否定更容易。