MATLAB Answers

xRobot
0

Comparing Two String Arrays

Asked by xRobot
on 19 Nov 2019 at 21:22
Latest activity Commented on by Sean de Wolski
on 19 Nov 2019 at 22:27
Hello,
I am trying to compare two string arrays to each other to see if any of the elements in one string array are in the other string array. I assumed the best approach was to use "any" and "strcmp".
This is my code. I was able to make it work if i placed "dad" as the first elment in 'stringMe'. However when I set the first element in stringMe to "mom", it did not work. Any suggestions or advice are greatly appreciated.
string = ["dad" "hey" "mom"];
stringMe= ["mom" "bob" "ted"];
if any(strcmp(string,stringMe))
disp('hello');
end

  0 Comments

Sign in to comment.

Tags

2 Answers

Answer by Image Analyst
on 19 Nov 2019 at 21:28
 Accepted Answer

Try intersect():
string = ["dad" "hey" "mom"];
stringMe= ["mom" "bob" "ted"];
inBoth = intersect(string, stringMe)
if ~isempty(inBoth)
message = sprintf('"%s" is in both', inBoth);
uiwait(helpdlg(message));
end

  1 Comment

xRobot
on 19 Nov 2019 at 22:11
Very helpu! Thanks!

Sign in to comment.


Answer by David Hill on 19 Nov 2019 at 21:36

if sum(ismember(string,stringMe))>0
disp('hello');
end

  1 Comment

Sean de Wolski
on 19 Nov 2019 at 22:27
if nnz()
instead of sum>0

Sign in to comment.