比较不同维度的字符串

时间:2016-04-05 10:41:54

标签: string matlab strcmp

我有字符串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'} 

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

1 个答案:

答案 0 :(得分:2)

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

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);

如果你想坚持使用Strings,你可以做一些更有效的事情:

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.