Left join for cell arrays in MATLAB

I have 2 cell arrays in MATLAB, for example:

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

and second:

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

I want to make a SQL left join, so I will have all the values ​​from B and their matches with A. If they do not appear in A, it will be "0". means:

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

did not find a suitable function for reference. Thank you

+4
source share
1 answer

Approach No. 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 in B  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 Execution -

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 No. 2

If you want to work with numbers in 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 in B  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 Execution -

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'
+2
source

All Articles