MATLAB Answers

find element inside cell

1 view (last 30 days)
NA
NA on 4 Mar 2019
Commented: NA on 4 Mar 2019
A=[1,2,3,4];
B=[5,6,7,8,9,10,11];
C=[12,13,14];
D=[14,15,16,17,18,19];
F=[20,21,22,23,24,25,26,27];
mes={[3,25],[14,10],[19,20],[26,4],[24,26],[1,8],[16,27],[22,11]};
check mes belongs to which group. [3,25] belongs to group A and F. [14,10] belongs to group C and B. [19,20] belongs to group D and F. [26,4] belongs to group F and A. [24,26] belongs to group F and F. [1,8] belongs to group A and B. [16,27] belongs to group D and F. [22,11] belongs to group F and B.
I want to have this result:
3 mes belongs to A.
3 mes belongs to B.
1 mes belongs to C.
2 mes belongs to D.
7 mes belongs to F.
I tried to use this code
for i=1:numel(mes)
if any(ismember(mes{i},A))
fprintf('\nbelongs to group A.\n');
end
if any(ismember(mes{i},B))
fprintf('\nbelongs to group B.\n');
end
if any(ismember(mes{i},C))
fprintf('\nbelongs to group C.\n');
end
if any(ismember(mes{i},D))
fprintf('\nbelongs to group D.\n');
end
if any(ismember(mes{i},F))
fprintf('\nbelongs to group F.\n');
end
end
but it does not give what I want.

  0 Comments

Sign in to comment.

Accepted Answer

KSSV
KSSV on 4 Mar 2019
Edited: KSSV on 4 Mar 2019
S = cell([],1) ;
A=[1,2,3,4];
B=[5,6,7,8,9,10,11];
C=[12,13,14];
D=[14,15,16,17,18,19];
F=[20,21,22,23,24,25,26,27];
mes={[3,25],[14,10],[19,20],[26,4],[24,26],[1,8],[16,27],[22,11]};
data = {A B C D F} ;
E = {'A' 'B' 'C' 'D' 'F'} ;
for i = 1:length(data)
count = 0 ;
for j = 1:length(mes)
[c,ia] = ismember(mes{j},data{i}) ;
if any(c)
count = count+1 ;
end
end
S{i} = sprintf('%d mes{%d} belongs to %s',count,i,E{i}) ;
end

  6 Comments

Show 3 older comments
NA
NA on 4 Mar 2019
how can I save fprintf here?
KSSV
KSSV on 4 Mar 2019
Edited code again..
NA
NA on 4 Mar 2019
Thanks

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!