String matrix compare to get common in rows

2 visualizaciones (últimos 30 días)
Touts Touts
Touts Touts el 26 de Jun. de 2019
Comentada: Touts Touts el 28 de Jun. de 2019
Deal all, i have a problem to compare two string matrix :
A1 = {'AA', 'b' ; 'cc', 'ff'}
A2 = {'ee', 'AA' ; 'hhh', 'm'}
strcmp(A1,A2)
I get
A1 =
'AA' 'b'
'cc' 'ff'
A2 =
'ee' 'AA'
'hhh' 'm'
ans =
0 0
0 0
But i need to get
'AA' is common between A1 iand A2 in the row 1
Best regard

Respuesta aceptada

Stephen23
Stephen23 el 28 de Jun. de 2019
Editada: Stephen23 el 28 de Jun. de 2019
>> A1 = {'AA', 'b' ; 'cc', 'ff' ; 'tt', 'kk'; 'XX', 'b'; 'AA', 'b'};
>> A2 = {'ee', 'AA' ; 'hhh', 'm'; 'kk', 'o'; 'ee', 'XX'; 'AA', 'b'};
>> X = cell2mat(cellfun(@ismember,num2cell(A1,2),num2cell(A2,2),'uni',0));
>> [R,~] = find(X);
>> [~,Y] = sort(R);
>> C = [A1(X),num2cell(R)].';
>> fprintf('''%s'' common at row %d\n',C{:,Y})
'AA' common at row 1
'kk' common at row 3
'XX' common at row 4
'AA' common at row 5
'b' common at row 5
  3 comentarios
Stephen23
Stephen23 el 28 de Jun. de 2019
"...is it possible to ignore the empty values"
Of course, just add this line after X is defined:
X = X & ~cellfun(@isempty,A1);
Touts Touts
Touts Touts el 28 de Jun. de 2019
Thanks a lot dear Stephen Cobeldick

Iniciar sesión para comentar.

Más respuestas (1)

Geoff Hayes
Geoff Hayes el 27 de Jun. de 2019
Touts - consider using ismember to check to see if any string of A1 matches with any string of A2
>> ismember(A1,A2)
ans =
1 0
0 0
  5 comentarios
Stephen23
Stephen23 el 28 de Jun. de 2019
Editada: Stephen23 el 28 de Jun. de 2019
@Touts Touts: repeating and clarifying Geoff Hayes's questions, which you did not answer:
  1. what happens if 'AA' occurs on different rows?
  2. what happens if 'AA' occurs multiple times within one matrix?
Touts Touts
Touts Touts el 28 de Jun. de 2019
Please, i need all the common between A1 and A2 and their rows
A1 = {'AA', 'b' ; 'cc', 'ff' ; 'tt', 'kk'; 'XX', 'b'; 'AA', 'b'}
A2 = {'ee', 'AA' ; 'hhh', 'm'; 'kk', 'o'; 'ee', 'XX'; 'AA', 'b'}
so
A1 =
'AA' 'b'
'cc' 'ff'
'tt' 'kk'
'XX' 'b'
'AA' 'b'
A2 =
'ee' 'AA'
'hhh' 'm'
'kk' 'o'
'ee' 'XX'
'AA' 'b'
I need
  • 'AA' common at row N° :1
  • 'kk' common at row N° :3
  • 'XX' common at row N° :4
  • 'AA' common at row N° :5
  • 'b' common at row N° :5
Any common at any row
Best regard

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by