seach string in arraycell and find idx

4 Ansichten (letzte 30 Tage)
piero
piero am 18 Sep. 2023
Beantwortet: David Hill am 18 Sep. 2023
C = {'A',31;
'B',5;
'C',3}
C = 3×2 cell array
{'A'} {[31]} {'B'} {[ 5]} {'C'} {[ 3]}
idx = find(ismember(C,{'A'}))
Error using cell/ismember
Input A of class cell and input B of class cell must be cell arrays of character vectors, unless one is a character vector.

Akzeptierte Antwort

David Hill
David Hill am 18 Sep. 2023
C = {'A',31;
'B',5;
'C',3};
idx = find(ismember(C(:,1),{'A'}))
idx = 1

Weitere Antworten (1)

Dyuman Joshi
Dyuman Joshi am 18 Sep. 2023
When using ismember, if any of the input is a Cell array, it is expected that it will be a cell array of character vectors.
> which is what the error states
> which is mentioned in the documentation as well - Input Arguments for ismember()
But C is not a homogenueous cell array of character vectors, it has numeric data as well. So the above code does not work.
Use (the more robust) strcmp instead -
C = {'A',31;
'B',5;
'C',3}
C = 3×2 cell array
{'A'} {[31]} {'B'} {[ 5]} {'C'} {[ 3]}
%Comparing with cell array of character vector
idx = find(strcmp(C,{'A'}))
idx = 1
%Comparing with character
idx = find(strcmp(C,'A'))
idx = 1
%Comparing with string
idx = find(strcmp(C,"A"))
idx = 1

Kategorien

Mehr zu Numeric Types finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by