MATLAB中单元格数组的左连接 [英] Left join for cell arrays in MATLAB
本文介绍了MATLAB中单元格数组的左连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在MATLAB中有2个单元格数组,例如:
I've 2 cell arrays in MATLAB, for example:
A= {jim,4,paul,5 ,sean ,5,rose, 1}
第二个:
B= {jim, paul, george, bill, sean ,rose}
我想进行SQL左连接,所以我将拥有B中的所有值以及A中的它们的匹配项.如果它们未出现在A中,那么它将为'0'.表示:
I want to make an SQL left join so I'll have all the values from B and their match from A. If they don't appear in A so it will be '0'. means:
C= {jim, 4, paul, 5, george, 0, bill, 0, sean, 5, rose, 1}
找不到任何相关的功能来寻求帮助. 谢谢.
didn't find any relevant function for help. thanks.
推荐答案
方法1
%// Inputs
A= {'paul',5 ,'sean' ,5,'rose', 1,'jim',4}
B= {'jim', 'paul', 'george', 'bill', 'sean' ,'rose'}
%// Reshape A to extract the names and the numerals separately later on
Ar = reshape(A,2,[]);
%// Account for unsorted A with respect to B
[sAr,idx] = sort(Ar(1,:))
Ar = [sAr ; Ar(2,idx)]
%// Detect the presence of A's in B's and find the corresponding indices
[detect,pos] = ismember(B,Ar(1,:))
%// Setup the numerals for the output as row2
row2 = num2cell(zeros(1,numel(B)));
row2(detect) = Ar(2,pos(detect)); %//extracting names and numerals here
%// Append numerals as a new row into B and reshape as 1D cell array
out = reshape([B;row2],1,[])
代码运行-
A =
'paul' [5] 'sean' [5] 'rose' [1] 'jim' [4]
B =
'jim' 'paul' 'george' 'bill' 'sean' 'rose'
out =
'jim' [4] 'paul' [5] 'george' [0] 'bill' [0] 'sean' [5] 'rose' [1]
方法2
如果要使用单元格数组中的数字作为字符串,则可以使用此修改后的版本-
Approach #2
If you want to work with the numerals in the cell arrays as strings, you can use this modified version -
%// Inputs [Please edit these to your actual inputs]
A= {'paul',5 ,'sean' ,5,'rose', 1,'jim',4};
B= {'jim', 'paul', 'george', 'bill', 'sean' ,'rose'}
%// Convert the numerals into string format for A
A = cellfun(@(x) num2str(x),A,'Uni',0)
%// Reshape A to extract the names and the numerals separately later on
Ar = reshape(A,2,[]);
%// Account for unsorted A with respect to B
[sAr,idx] = sort(Ar(1,:));
Ar = [sAr ; Ar(2,idx)];
%// Detect the presence of A's in B's and find the corresponding indices
[detect,pos] = ismember(B,Ar(1,:));
%// Setup the numerals for the output as row2
row2 = num2cell(zeros(1,numel(B)));
row2 = cellfun(@(x) num2str(x),row2,'Uni',0); %// Convert to string formats
row2(detect) = Ar(2,pos(detect)); %//extracting names and numerals here
%// Append numerals as a new row into B and reshape as 1D cell array
out = reshape([B;row2],1,[])
代码运行-
B =
'jim' 'paul' 'george' 'bill' 'sean' 'rose'
A =
'paul' '5' 'sean' '5' 'rose' '1' 'jim' '4'
out =
'jim' '4' 'paul' '5' 'george' '0' 'bill' '0' 'sean' '5' 'rose' '1'
这篇关于MATLAB中单元格数组的左连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文