# Joining two matrices on a common column vector *

import numpy as np # Don't use, for reference only def cartesian_product(A, B, on): Ax, Ay = A.shape Bx, By = B.shape Acol, Bcol = on C = np.zeros((Ax, Ay + By - 1)) C[0:Ax, 0:Ay] = A if np.array_equal(A[:, Acol], B[:, Bcol]): B = np.delete(B, Bcol, 1) C[0:Ax + Bx, Ay:Ay + By -1] = B return C return None # Better def cartesian_product(A, B, on): Acol, Bcol = on if np.array_equal(A[:, Acol], B[:, Bcol]): B = np.delete(B, Bcol, 1) return np.hstack((A, B)) # Example 1 A = np.array([ [3,4,5,9], [5,6,7,4], [7,2,3,6] ]) B = np.array([ [5,9,3,1], [4,4,5,2], [2,6,8,5] ]) print(cartesian_product(A, B, [3, 1])) # [col in A, col in B] """ [[3 4 5 9 5 3 1] [5 6 7 4 4 5 2] [7 2 3 6 2 8 5]] """ # Example 2 A = np.array([ [1.4, 2.1, 3.5, 7.2, 4.8, 11.2, 5.7, 3.4], [4.6, 3.8, 3.7, 8.5, 9.3, 6.4, 2.1, 0.9], [6.5, 5.4, 3.2, 5.7, 2.4, 1.7, 4.7, 1.7], [7.6, 6.4, 7.0, 5.0, 3.2, 4.1, 3.7, 1.9] ]) B = np.array([ [7.4, 3.5, 6.3, 6.1, 10.4, 4.8, 4.4], [5.5, 3.4, 6.7, 3.9, 9.8, 9.3, 6.1], [4.6, 7.2, 8.4, 2.9, 4.4, 2.4, 11.2], [7.2, 7.7, 5.4, 4.0, 6.5, 3.2, 6.9] ]) print(cartesian_product(A, B, [4, 5])) """ [[1.4, 2.1, 3.5, 7.2, 4.8, 11.2, 5.7, 3.4, 7.4, 3.5, 6.3, 6.1, 10.4, 4.4], [4.6, 3.8, 3.7, 8.5, 9.3, 6.4, 2.1, 0.9, 5.5, 3.4, 6.7, 3.9, 9.8, 6.1], [6.5, 5.4, 3.2, 5.7, 2.4, 1.7, 4.7, 1.7, 4.6, 7.2, 8.4, 2.9, 4.4, 11.2], [7.6, 6.4, 7., 5., 3.2, 4.1, 3.7, 1.9, 7.2, 7.7, 5.4, 4., 6.5, 6.9]] """
* similar to Cartesian product when joining database tables