Search code examples
matlableft-joincell-array

Left join for cell arrays in MATLAB


I've 2 cell arrays in MATLAB, for example:

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

and the second:

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

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.


Solution

  • Approach #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,[])
    

    Code run -

    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]
    

    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,[])
    

    Code run -

    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'