kikki
kikki

Reputation: 31

Compare strings of different dimensions

I have the string s1 and 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

{'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. Can you help me?

Upvotes: 0

Views: 80

Answers (1)

GameOfThrows
GameOfThrows

Reputation: 4510

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:

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. so the ismember function is your best choice.

To generate the "s1 and its substrings", you can use combnk such as:

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

Upvotes: 2

Related Questions