How to find a element in cell array
15 views (last 30 days)
Show older comments
Nguyen Trung
on 29 Apr 2012
Edited: ibrahim Salim
on 24 Jan 2018
hi! I have a problem with matlab: I have a string cell array with variousty size (1024*1) and i must be find one string if it is in cell array and location of it in cell array. any one help me? thank ect
s{1,1}={'01' '02' '0123' '04' '14' '0124' '34' '03' '0134' '23' '24' '0234' '12' '13' '1234'}
s{2,1}= {'012' '024' '3' '034' '023' '1' '123' '013' '4' '014' '134' '2' '234' '124' '0'}
i must find '4' if is appear in s and location of '4' in cell array s.
1 Comment
Stephen23
on 12 Mar 2015
Edited: Stephen23
on 12 Mar 2015
Although this has already been accepted, there is a neater solution using a better data structure of a cell array of strings (rather than cell array of cell arrays), together with strfind. This returns the location indices in a cell array the same size as s:
>> s(2,:)={'012','024','3','034','023','1','123','013','4','014','134'};
>> s(1,:)={'01','02','0123','04','14','0124','34','03','0134','23','24'};
>> strfind(s,'4')
ans =
[] [] [] [2] [2] [4] [2] [] [4] [] [2]
[] [3] [] [3] [] [] [] [] [1] [3] [3]
Accepted Answer
Andrei Bobrov
on 29 Apr 2012
out = cellfun(@(x)regexp(x,'4'),s,'un',0);
ADDED on Nguyen's answer :)
out = cellfun(@(x)regexp(x,'^4$'),s,'un',0)
or:
out = cellfun(@(x)ismember(x,'4'),s,'un',0)
3 Comments
Image Analyst
on 19 Jan 2016
mhm's "flag" moved here so that it is a comment rather than a flag: Then I removed the flag.
find element in cell
ibrahim Salim
on 24 Jan 2018
Edited: ibrahim Salim
on 24 Jan 2018
Hello, I'd like to ask How can I delete zeros(logical values) from cell 'out'? Thanks
More Answers (1)
Richard Brown
on 29 Apr 2012
Can you define your cell array differently (can it be a 2D cell array, rather than a cell array of cell arrays?) If so, then
s(1,:)={'01' '02' '0123' '04' '14' '0124' '34' '03' '0134' '23' '24' '0234' '12' '13' '1234'}
s(2,:)= {'012' '024' '3' '034' '023' '1' '123' '013' '4' '014' '134' '2' '234' '124' '0'}
[I, J] = find(strcmp(s, '4'))
4 Comments
Richard Brown
on 30 Apr 2012
OK, so long as each entry of s has the same number of entries (15 in this case), then first run
s = vertcat(s{:})
See Also
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!