Comparing Two String Arrays

109 ビュー (過去 30 日間)
xRobot
xRobot 2019 年 11 月 19 日
コメント済み: Sean de Wolski 2019 年 11 月 19 日
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

採用された回答

Image Analyst
Image Analyst 2019 年 11 月 19 日
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 件のコメント
xRobot
xRobot 2019 年 11 月 19 日
Very helpu! Thanks!

サインインしてコメントする。

その他の回答 (1 件)

David Hill
David Hill 2019 年 11 月 19 日
if sum(ismember(string,stringMe))>0
disp('hello');
end
  1 件のコメント
Sean de Wolski
Sean de Wolski 2019 年 11 月 19 日
if nnz()
instead of sum>0

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeSimulink についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by