Find one of strings into cell array

1 回表示 (過去 30 日間)
Laercio Barbosa
Laercio Barbosa 2018 年 10 月 19 日
コメント済み: Laercio Barbosa 2018 年 10 月 23 日
Hello all!
I have an cell array 'inputs' with strings and numbers and I need find where one of the strings from an another cell array of strings is located.
inputs = {'str1' 'str2' 'str3' single(1.5) 'str4' uint16(500) 'str5' single(2)};
In order to check if 'str1' belongs to 'inputs' and gets its index I do:
find(strcmpi(inputs, 'str1'))
ans = 1
But if I want to find where one string of a cell array of strings is located
find(strcmpi(inputs, {'str1' 'str3' 'str4'}))
Error using strcmpi
Inputs must be the same size or either one can be a scalar.
I would like to see
ans = 1 3 5
Also 'ismember' doesn't work as 'inputs' has numbers as well. Then I wrote:
cellfun(@(c)strcmpi(c,inputs),{'str1' 'str3' 'str4'},'UniformOutput',false)
ans = 1×3 cell array
{1×8 logical} {1×8 logical} {1×8 logical}
Now I have the logical results as 1x3 of 1x8 and, if I could perform an OR operation and bring this 1x3(1x8) to 1x8, I could apply 'find' and get the right indexes. I have tried to use OR together with 'cellfun' but I failed miserably. At this point I reached this thread:
The solution was to use 'ismember' what is not possible in my case. So my questions are:
  1. Is there any way to perform OR operation with this 1x3(1x8) cell array and bring it to 1x8 without FOR loop?
  2. Is there another approach to this problem?
Thanks in advance for your support!

採用された回答

Walter Roberson
Walter Roberson 2018 年 10 月 19 日
   find(ismember(cellfun(@(V) lower(char(V)), inputs, 'uniform', 0), cellfun(@lower, {'str1', 'str3', 'str4'}, 'uniform', 0)))

or

find(any(cell2mat(cellfun(@(c)strcmpi(c,inputs).', {'str1' 'str3' 'str4'}, 'UniformOutput',false)),2))

The first of those has the small flaw that a non-character value that happened to have the same numeric value as a single char target string could be recognized. For example 98 could be matched as if it were 'b'. Also, not everything can be converted to char -- logical cannot, struct cannot.

  1 件のコメント
Laercio Barbosa
Laercio Barbosa 2018 年 10 月 23 日
Thank you, Walter!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by