How to use ismember to assign values from one cell array to another cell array

10 visualizaciones (últimos 30 días)
Hi,
I have two cell arrays of unequal lengths
x = {'C', 'A', 'B', 1; 'C', 'A', 'B', 1; 'C', 'A', 'B', 2; 'B', 'A', 'D', 5}
y = {2, 'A', 'B', 'O'; 2, 'A', 'D', 'O';}
and I am trying to use ismember to assign values from cell array x to cell array y based on two conditions: if the values of the second and third colum of cell array x match the values of the second and third colum of cell array y, then I want to replace the values of the 4th column of cell array y with the values of the first column of cell array x (sorry if its a bit confusing). In other words the desired output looks like this:
y = {2, 'A', 'B', 'C'; 2, 'A', 'D', 'B'}
My attempted code is below.
xx = [x(2:end, 2), x(2:end, 3)]
yy = [y(2:end, 2), y(2:end, 3)]
[idx, idy] = ismember(xx, yy)
y(idx, 4) = x(idy(idx), 1)
  1 comentario
madhan ravi
madhan ravi el 30 de Abr. de 2020
While talking about the columns you neglected about the rows? x has four rows and y has 2 rows?

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 30 de Abr. de 2020
Assuming that each cell contains exactly one character:
>> [idx,idy] = ismember(cell2mat(y(:,2:3)),cell2mat(x(:,2:3)),'rows');
Or, as most likely each cell contains multiple characters in a vector, you can do this:
>> [idx,idy] = ismember(strcat(y(:,2),'*',y(:,3)),strcat(x(:,2),'*',x(:,3)));
And then simply:
>> y(idx,4) = x(idy(idx),1)
y =
[2] 'A' 'B' 'C'
[2] 'A' 'D' 'B'

Más respuestas (0)

Categorías

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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by