Find one of strings into cell array

조회 수: 2 (최근 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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by