Clear Filters
Clear Filters

Finding Indices of Cells Containing Certain Text in Mixed Arrays (Both Numbers and Strings)

11 views (last 30 days)
I sometimes have to deal with excel files that contain columns of the following format:
i.e. a combination of numbers-only and number+text cells. What I need to do is to find cells that contain only the number '22' and have the array numbers in a new array. In this case the new array should be: [1 7 13 14 15]. Then I would like to create another array that contains the row numbers of the cells that contain the exact string '22 EZ'. In the case of this example that new array should be: [2 3 4 8]. How can I do this? So far I have tried to read the imput file using : [NUMx,STRx,RAWx]=xlsread('Inputfile.xlsx') But I am not sure which class I need to use in order to perform the search properly.
Saeid

Accepted Answer

Stephen23
Stephen23 on 17 Dec 2016
Edited: Stephen23 on 17 Dec 2016
Untested, but something like this should work:
[NUMx,STRx,RAWx]=xlsread('Inputfile.xlsx')
find(cellfun(@(x)isnumeric(x)&&x==22,RAWx))
find(cellfun(@(x)ischar(x)&&strcmp(x,'22 EZ'),RAWx))
for example:
>> X = {22;'22 EZ';'22 EZ';'22 EZ';25;'TOLOUL';22;'22 EZ';25;'N 10';22;25;22;22;22;'N415'};
>> find(cellfun(@(x)isnumeric(x)&&x==22,X))
ans =
1
7
11
13
14
15
>> find(cellfun(@(x)ischar(x)&&strcmp(x,'22 EZ'),X))
ans =
2
3
4
8
  3 Comments
Saeid
Saeid on 18 Dec 2016
Edited: Saeid on 18 Dec 2016
Hi Stephen,
I can already use the method you mentioned, but sometimes the phrase '22 EZ' is just part of a larger phrase. The program in this form seems to only recognize the exact phrase '22 EZ' and if it is longer in the original excel cell (e.g. 'LAB 22 EZ 11_14') it will not find it. Is there a solution for that too?
Saeid
Stephen23
Stephen23 on 21 Dec 2016
Replace the strcmp with strfind, isempty, and a negation:
>> ~isempty(strfind('LAB 22 EZ 11_14','22 EZ'))
ans = 1

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!