How to use ismember to assign values from one cell array to another cell array
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
madhan ravi
am 30 Apr. 2020
While talking about the columns you neglected about the rows? x has four rows and y has 2 rows?
Akzeptierte Antwort
Stephen23
am 30 Apr. 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'
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!