2015-05-21 178 views
0

我必须creade一个函数,有两个输入端:字符串单元阵列(姑且称之为txt)和一个字符串(姑且称之为str)。该函数必须删除单元格矢量txt的每个元素,其字符串与str相同或包含str作为子字符串。 对于我已经尝试过了片刻以下几点:查找某个字符串在另一字符串在Matlab

function c = censor(txt,str) 
    c = txt; 
    n = length(c); 
    for i = 1:n 
     a = c{ i }; 
     a(a == str) = []; 
     c{i} = a; 
    end 
end 

但它不工作,它给出了Matrix dimensions must agree.我明白,这可能是因为str有不止一个字符的错误,但我不t知道如何找到str是否包含在单元阵列txt的任何字符串中。

+2

看看strfind。 http://se.mathworks.com/help/matlab/ref/strfind.html –

+0

不错,它做我需要的,但问题是当巧合出现不止一次。一旦找到所有的巧合,我不知道如何去除每个元素。 – Hec46

回答

3

正如Anders指出的那样,您希望使用strfind来查找其他字符串内部的字符串。这是您可以编写函数的一种方式。基本上整个应用strfind整个txt单元阵列,然后删除有匹配的条目。

代码:

function censor(txt,str) 
clc 
clear 

%// If no input are supplied..demo 
if nargin ==0 

    str = 'hello'; 
    txt = {'hellothere' 'matlab' 'helloyou' 'who are you' 'hello world'}; 
end 

IsItThere = strfind(txt,str) 

现在IsItThere是一个单元阵列与一些1和空单元格:

IsItThere = 

    [1] [] [1] [] [1] 

让我们填补空白单元格为0,所以我们可以在以后进行逻辑索引:

IsItThere(cellfun('isempty',IsItThere))={0} 

在其中找到一个匹配发生索引:

IndicesToRemove = find(cell2mat(IsItThere)) 

IndicesToRemove = 

    1  3  5 

并卸下电池:

txt(IndicesToRemove) = []; 

txt现在看起来是这样的:

txt = 

    'matlab' 'who are you' 

end 

如果你喜欢,你可以结合几个步骤在一起,但我希望是很清晰: )

这里是整个代码,您可以在.m文件复制/粘贴:

function censor(txt,str) 
clc 
clear 

%// If no input are supplied..demo 
if nargin ==0 

    str = 'hello'; 
    txt = {'hellothere' 'matlab' 'helloyou' 'who are you' 'hello world'}; 
end 

IsItThere = strfind(txt,str) 

IsItThere(cellfun('isempty',IsItThere))={0} 

IndicesToRemove = find(cell2mat(IsItThere)) 

txt(IndicesToRemove) = []; 
txt 
end 
+0

您的方法适用于您的示例,但出于某种原因,当单元格数组的每个元素都是一个句子并且'str'多次出现时,它都不起作用。有关如何改进此方法的任何想法?这真的很好,但我不知道如何使它适用于多个巧合的句子。例如,使用美国国歌的前8行和'str ='the'',我得到:[IsItThere = [24] [30] [43] [6] [1x2 double] [1x2 double] [0] [1x4 double]' – Hec46

+0

@ Hec46当有多处出现时,'strfind'给出'str'开始的索引。你可以在IsItThere(cellfun('isempty',IsItThere))= {0}之前使用'IsItThere(〜cellfun('isempty',IsItThere))= {1} –

相关问题