partial match of 2 string vectors with different lenghts

Hi everyone,
I hope you can help me. I have two 2 string arrays (str1 and str2) with different lengths. For instance,
str1= ["16-10-2017 09:20:00"; "16-10-2017 09:21:00"; "16-10-2017 09:22:00"; "16-10-2017 09:23:00"] ]
str2= ["16-10-2017 09:21:00_water"; "16-10-2017 09:23:00_coffee"] ]
I would like to:
(1) match the first 19 characters of a str2 (in this case it is 16-10-2017 09:21:00) with str1
(2) create str3 that will give me a string array like this str3=[0;"16-10-2017 09:21:00_water";0;"16-10-2017 09:23:00_coffee"] So when there is an overlap use the value in str2 in str3, when there is no overlap use 0 or NAN.
Thanks,

Answers (1)

Something like this:
str1= ["16-10-2017 09:20:00"; "16-10-2017 09:21:00"; "16-10-2017 09:22:00"; "16-10-2017 09:23:00"];
str2= ["16-10-2017 09:21:00_water"; "16-10-2017 09:23:00_coffee"];
temp=arrayfun(@extract_date,str2);
L=ismember(str1,temp);
str3=str1;
str3(~L)=0;
str3(L)=str2;
function date=extract_date(str)
str=char(str);
date=string(str(1:19));
end

5 Comments

I tested this for:
str1= ["16-10-2017 09:20:00"; "16-10-2017 09:21:00"; "16-10-2017
09:22:00"; "16-10-2017 09:23:00"];
str2= ["16-10-2017 09:21:00_water"];
And got str3 =
4×1 string array
"16-10-2017 09:21:00_water"
"0"
"16-10-2017 09:21:00_water"
"16-10-2017 09:21:00_water"
From my understanding the correct output should be:
str3=[0;"16-10-2017 09:21:00_water";0;0]
Sorry, my mistake, I switched up the ~L and L. I'll edit my answer.
Thanks, the code works with these strings. However, I tried the code with my original data and it did give me an error. str1's value is 6196x1 and str2's value is 14x1.
(In an assignment A(:) = B, the number of elements in A and B must be the same. Error in matching_code (line 5) str3(L)=str2;)
Then the dates in str2 are non-unique. So which should be selected?

Sign in to comment.

Categories

Asked:

PH
on 6 Jun 2018

Commented:

Rik
on 7 Jun 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!