Clear Filters
Clear Filters

How can I use the find function for cell arrays to search for particular cell vector values

3 views (last 30 days)
Suppose I have a cell array:
EC = {[1,2,1,1] [1,3,1,1] [1,4,1,1] [1,1,1,2]}
I need a way to index where the values of the cells = [1,3,1,1] or [1,1,1,2] such that MATLAB returns: [2,4] for the 2nd and 4th cells of array EC.
I've been trying to use the find function, but it doesn't appear you can use that for cell arrays...

Accepted Answer

KSSV
KSSV on 21 Mar 2017
EC = {[1,2,1,1] [1,3,1,1] [1,4,1,1] [1,1,1,2]} ;
k = {[1,3,1,1] [1,1,1,2]} ;
EC = cell2mat(EC(:)) ;
k = cell2mat(k(:)) ;
[val,idx] = ismember(k,EC,'rows') ;
idx
  2 Comments
Kevin
Kevin on 27 Mar 2017
What does the "val" do? It just seems to be creating a vector of ones corresponding to the length of k (whatever the # of cells I'm looking for), which in this example happens to be 2. How is this ever useful?
Reading help ismember, which calls it LIA (not sure why) says it's just that, an array of same size as 'k', containing true where the elements of 'k' are in 'EC' and false otherwise.
I can understand wanting an index like LOCB (as they call it), and can see how you might just want the number of cases where k is in EC, but how is it useful to just get an array of ones?
Jan
Jan on 27 Mar 2017
Edited: Jan on 27 Mar 2017
@Kevin: In the general case this command searchs if an element of A occurres in B:
[LIA, LocB] = ismember(A, B);
LIA is a logical index vector related to A (L I A), which is TRUE, if the corresponding element of A occurres in B, while LocB is the index of the matching element of B.

Sign in to comment.

More Answers (1)

John BG
John BG on 25 Mar 2017
hi Kevin
the following builds a 2 columns cell where 1st column is just the numeral coinciding with EC amount of elements and 2nd column is variable length indicating what vector of D matches the i-th element of D
EC = {[1,2,1,1] [1,3,1,1] [1,4,1,1] [1,1,1,2]}
D={[1,3,1,1] [1,1,1,2] }
match={}
for k=1:1:size(EC,2)
match{k,1}=k;
for s=1:1:size(D,2)
if isequal(class(D{s}),class(EC{k})) && isequal(EC{k},D{s})
match{k}=[match{k} s];
end
end
end
match{:}
ans =
1
ans =
2 1
ans =
3
ans =
4 2
this script can be enhanced to include EC and D containing different classes.
if you find these lines useful would you please mark my answer as Accepted Answer?
To any other reader, if you find this answer of any help please click on the thumbs-up vote link,
thanks in advance for time and attention
John BG

Community Treasure Hunt

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

Start Hunting!