2016-04-05 259 views
0

我有串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),但我沒有獲得預期的結果。你可以幫我嗎?

回答

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

如果你想堅持的字符串,你可以做這樣的事情這是更有效:

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. 
+1

對於'str2double'你不需要包裝在'cellfun'和'cellmat'。只要做'str2double(s2)',因爲它可以接受一個字符串的單元數組。 – Suever

+0

@Suever ohhh很好,沒有看到那個 – GameOfThrows