Find cell containing part of a string

13 Ansichten (letzte 30 Tage)
KAE
KAE am 26 Okt. 2017
Kommentiert: KAE am 27 Okt. 2017
I would like to find the elements of a cell array that contain part of a specified string.
colorList = {'Red', 'Green', 'Blue', 'Purple'}; % List of values to match with
stringToCheck = 'Blue 23948723'; % String we are trying to match
I would like to return index=3 of colorList since that entry contains the stringToCheck text of 'Blue'. How can I do this?

Akzeptierte Antwort

Cedric
Cedric am 26 Okt. 2017
Bearbeitet: Cedric am 26 Okt. 2017
If you cannot assume that keywords are separated by white spaces:
>> find(cellfun(@(x)~isempty(strfind(stringToCheck,x)), colorList))
ans =
3
  2 Kommentare
KAE
KAE am 26 Okt. 2017
Bearbeitet: KAE am 26 Okt. 2017
They may not be, I hadn't thought of that so thanks.
Cedric
Cedric am 26 Okt. 2017
My pleasure!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

per isakson
per isakson am 26 Okt. 2017
Bearbeitet: per isakson am 26 Okt. 2017
>> find( ismember( colorList, strsplit( stringToCheck ) ) )
ans =
3
or
>> find( ismember( colorList, strsplit( stringToCheck, {'\s','\.',','} ...
, 'CollapseDelimiters',true, 'DelimiterType','RegularExpression' ) ) )
ans =
3
if the color name is followed by a period or comma, e.g. "Blue.". And what about upper and lower case, e.g "blue"? And "Bluetooth"?
  1 Kommentar
KAE
KAE am 26 Okt. 2017
Thank you, this works and your scenarios are useful too.

Melden Sie sich an, um zu kommentieren.


Akira Agata
Akira Agata am 26 Okt. 2017
If your MATLAB is R2016b or later version, you can use contains function, like:
idx = cellfun(@(x) contains(stringToCheck,x),colorList);
The answer is:
>> colorList(idx)
ans =
{'Blue'}
  1 Kommentar
KAE
KAE am 27 Okt. 2017
Thank you, this syntax is easier to read and thus remember than then other ones.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Line Plots finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by