比较不同维度的字符串

Compare strings of different dimensions

我有字符串 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) 但我没有得到预期的结果。你能帮帮我吗?

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

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 个字符串和 returns 一个逻辑,在你的情况下,你面临 5*65 个操作,这通常很耗时且处理起来很糟糕.所以ismember函数是你最好的选择。

要生成"s1 and its substrings",可以使用combnk,例如:

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