在MATLAB中左键连接单元格数组

我在MATLAB中有2个单元格数组,例如:

A= {jim,4,paul,5 ,sean ,5,rose, 1}

第二个:

B= {jim, paul, george, bill, sean ,rose}

我想做一个SQL左连接,所以我将得到B中的所有值和它们与A的匹配.如果它们没有出现在A中,那么它将为’0′.手段:

C= {jim, 4, paul, 5, george, 0, bill, 0, sean, 5, rose, 1}

没有找到任何相关的帮助功能.
谢谢.

最佳答案 方法#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

如果您希望将单元格数组中的数字用作字符串,则可以使用此修改后的版本 –

%// 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'
点赞