I want to merge the content of two tables with identical variables, but for a given key variable value the columns 1:N in table 1 are filled and columns N+1:end in the other.
    5 views (last 30 days)
  
       Show older comments
    
This is what I would like to achieve: A = table({'a'}, 5, 15, 25, 0, 0, 0,'VariableNames',{'A1','A2', 'A3', 'A4', 'B1', 'B2', 'B3'}) A = A1 A2 A3 A4 B1 B2 B3  _
    'a'    5     15    25    0     0     0
>> B = table({'a'}, 0, 0, 0, 6, 12, 18,'VariableNames',{'A1','A2', 'A3', 'A4', 'B1', 'B2', 'B3'}) B = A1 A2 A3 A4 B1 B2 B3  _
    'a'    0     0     0     6     12    18
>> What operation would yield table C (matching the values of variable 'A1'): C = table({'a'}, 5, 15, 25, 6, 12, 18,'VariableNames',{'A1','A2', 'A3', 'A4', 'B1', 'B2', 'B3'}) C =
    A1     A2    A3    A4    B1    B2    B3
    ___    __    __    __    __    __    __
    'a'    5     15    25    6     12    18
0 Comments
Answers (1)
  Ramnarayan Krishnamurthy
    
 on 21 Sep 2017
        
      Edited: Ramnarayan Krishnamurthy
    
 on 21 Sep 2017
  
      Merging 2 tables on the basis of key variables and retaining only the common rows can be achieved using the 'innerjoin' function.
For the requirements in this question, we would need to manipulate the input data A and B, so that only the desired columns from both the tables are selected
 t = innerjoin(A(:,[1:4]),B(:,[1,5:end]),'LeftKeys',1,'RightKeys',1);
 t = 
    A1     A2    A3    A4    B1    B2    B3
    ___    __    __    __    __    __    __
    'a'    5     15    25    6     12    18
Additionally, to generalize the above code where N is the number of filled columns in Table 1:
N = 4;
t = innerjoin(A(:,[1:N]),B(:,[1,N+1:end]),'LeftKeys',1,'RightKeys',1);
The documentation for the 'innerjoin' function is available at: https://www.mathworks.com/help/matlab/ref/innerjoin.html
Hope this helps!
0 Comments
See Also
Categories
				Find more on Tables in Help Center and File Exchange
			
	Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
