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

2 ビュー (過去 30 日間)
Blue
Blue 2020 年 4 月 30 日
コメント済み: Blue 2020 年 4 月 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)
  1 件のコメント
madhan ravi
madhan ravi 2020 年 4 月 30 日
While talking about the columns you neglected about the rows? x has four rows and y has 2 rows?

サインインしてコメントする。

採用された回答

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 Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by