MATLAB Answers

Matching unequal cell arrays

10 ビュー (過去 30 日間)
Ronald
Ronald 2020 年 6 月 3 日
コメント済み: Ronald 2020 年 6 月 5 日
I have two unequal arrays and I want to match them to produce one array such that the unmatched cells are left empty i.e
A = {124,252,1252,225,598,999}
B = {598,'plant';
1252,'nil';
252,'blue'}
The result C;
C = {124,[];
252,'blue';
1252,'nil';
225,[];
598,'plant';
999,[]}

回答 (2 件)

TADA
TADA 2020 年 6 月 3 日
A = {124,252,1252,225,598,999};
B = {598,'plant';...
1252,'nil';...
252,'blue'};
[~, Ai_member, Bi_member] = intersect([A{:}], [B{:,1}]);
C = [A(:), cell(numel(A), 1)];
[C{Ai_member, 2}] = B{Bi_member, 2}
  3 件のコメント
Ronald
Ronald 2020 年 6 月 5 日
This is really good. Thank you very much!

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


Stephen Cobeldick
Stephen Cobeldick 2020 年 6 月 4 日
編集済み: Stephen Cobeldick 2020 年 6 月 4 日
Using tables:
>> TA = cell2table(A(:))
TA =
Var1
____
124
252
252
1252
225
225
598
598
999
>> TB = cell2table(B'')
TB =
Var1 Var2
____ _______
598 'plant'
1252 'nil'
252 'blue'
>> T = outerjoin(TA,TB,'MergeKeys',true)
T =
Var1 Var2
____ _______
124 ''
225 ''
225 ''
252 'blue'
252 'blue'
598 'plant'
598 'plant'
999 ''
1252 'nil'
Note that the output rows are sorted by the joining key. To keep the original order:
>> [T,X] = outerjoin(TA,TB,'MergeKeys',true);
>> T(X,:) = T
T =
Var1 Var2
____ _______
124 ''
252 'blue'
252 'blue'
1252 'nil'
225 ''
225 ''
598 'plant'
598 'plant'
999 ''

Community Treasure Hunt

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

Start Hunting!

Translated by