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

2 次查看(过去 30 天)
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)

采纳的回答

Stephen23
Stephen23 2020-4-30
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'

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by