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

3 次查看(过去 30 天)
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...

采纳的回答

KSSV
KSSV 2017-3-21
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 个评论
Kevin
Kevin 2017-3-27
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 2017-3-27
编辑:Jan 2017-3-27
@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.

请先登录,再进行评论。

更多回答(1 个)

John BG
John BG 2017-3-25
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by