【问题标题】:Compare strings of different dimensions比较不同维度的字符串
【发布时间】:2016-04-05 10:41:54
【问题描述】:

我有字符串 s1 和 s2

s1={'1' '631' '618' '574' '678'} 
s2={'1' '596' '674' '' '';'674' '631' '1' '631' '1';'641' '617' '674' '631' '654';'674' '673' '674' '673' '674';'674' '618' '1' '618' '631';'631' '1' '631' '674' '740';'739' '740' '733' '674' '631';'674' '673' '674' '1' '641';'618' '1' '631' '618' '631';'674' '631' '618' '631' '618';'674' '631' '1' '631' '625';'641' '642' '618' '631' '618';'618' '631' '1' '631' '1'}

我想比较 s1 和它的子串

{'1'}
{'1' '631'}
{'1' '631' '618'}
{'1' '631' '618' '574'}
{'1' '631' '618' '574' '678'}
{'631'}
{'631' '618'}
{'631' '618' '574'}
{'631' '618' '574' '678'}
{'618'}
{'618' '574'}
{'618' '574' '678'}
{'574'}
{'574' '678'}
{'678'} 

with s2: 我使用了 strcmp(s1,s2) 但我没有得到预期的结果。你能帮帮我吗?

【问题讨论】:

    标签: string matlab strcmp


    【解决方案1】:

    我强烈建议将所有字符串转换为数字并使用矩阵运算而不是字符串运算:

    S1 = cellfun(@str2num, s1)
    S2 = cell2mat(str2double (s2)) %// NOTE its str2double here which converts any empty string or char into a NaN
    

    现在进行比较,如果你想相交(我认为你是)

    [intersect ind] =  ismember(S2,S1);
    

    如果你想坚持使用字符串,你可以这样做更有效:

    ind=find(ismember(s2,s1{1}))
    >> ind =
    
     1
    19
    22
    28
    31
    37
    39
    47
    54
    65
    

    strcmp 的问题在于它比较 2 个字符串并返回一个逻辑,在您的情况下,您面临 5*65 操作,这通常是耗时且难以处理的。所以ismember函数是你最好的选择。

    要生成“s1及其子串”,可以使用combnk如:

    V = combnk(S1,1)
    V = combnk(S1,2) %//change 1 to 5 based on the combinations.
    

    【讨论】:

    • 对于str2double,您不需要将其包装在cellfuncellmat 中。只需执行str2double(s2),因为它可以接受一个字符串元胞数组。
    • @Suever 哦,不错,没看到
    猜你喜欢
    • 2013-02-12
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多