简体   繁体   English

比较不同尺寸的琴弦

[英]Compare strings of different dimensions

I have the string s1 and s2 我有字符串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'}

I want to compare s1 and its substrings 我想比较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: I have used strcmp(s1,s2) but I don't obtain the expected result. 使用s2:我使用过strcmp(s1,s2),但未获得预期的结果。 Can you help me? 你能帮助我吗?

I highly suggest converting all your strings in to numbers and use matrix operations instead of string operations: 我强烈建议您将所有字符串都转换为数字,并使用矩阵运算而不是字符串运算:

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

now do the compare, if you want intersect (which I think you are) 现在进行比较,如果您想相交(我想是)

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

If you want to stick with Strings, you can do something like this which is much more efficient: 如果您想坚持使用Strings,可以执行以下操作,效率更高:

ind=find(ismember(s2,s1{1}))
>> ind =

 1
19
22
28
31
37
39
47
54
65

The problem with strcmp is that it compares 2 strings and returns a logical, in your case, you are facing 5*65 operations, which is time consuming and terrible to process in general. strcmp的问题在于,它比较2个字符串并返回一个逻辑,在您的情况下,您将面临5 * 65的操作,这是耗时的,并且通常难以处理。 so the ismember function is your best choice. 因此ismember函数是您的最佳选择。

To generate the "s1 and its substrings", you can use combnk such as: 要生成“ s1及其子字符串”,可以使用combnk例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM