Find one of strings into cell array

1 visualización (últimos 30 días)
Laercio Barbosa
Laercio Barbosa el 19 de Oct. de 2018
Comentada: Laercio Barbosa el 23 de Oct. de 2018
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!

Respuesta aceptada

Walter Roberson
Walter Roberson el 19 de Oct. de 2018
   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.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by