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

10 vues (au cours des 30 derniers jours)
Blue
Blue le 30 Avr 2020
Commenté : Blue le 30 Avr 2020
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 commentaire
madhan ravi
madhan ravi le 30 Avr 2020
While talking about the columns you neglected about the rows? x has four rows and y has 2 rows?

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 30 Avr 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'

Plus de réponses (0)

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by