Home > Back-end >  How do I make a matrix from multiple lists of matrices?
How do I make a matrix from multiple lists of matrices?

Time:09-22

Hi I am trying to figure out how to create a matrix from other matrices. I have created 3 matrixes from certain calculations and have arrived at 3 matrices of shape (1200,3) each. 1200 represents the rows of number of data set. What I want to extract from each of this Matrix (A, B, C) is to put them in this order for the first of 1200 data points:

[[A[0][0], B[0][0], C[0][0]],    
 [A[0][1], B[0][1], C[0][1]],    
 [A[0][2], B[0][2], C[0][2]]]

This is what I have written so far:

def getRotationMatrix(acc_x_sample, acc_y_sample, acc_z_sample, mag_x_sample, mag_y_sample, mag_z_sample):
    a = np.transpose(np.array([acc_x_sample,acc_y_sample,acc_z_sample]))
    m = np.transpose(np.array([mag_x_sample,mag_y_sample,mag_z_sample]))

    B = np.cross(a,m) # (a x m)
    A = np.cross(B,a) 
    C = a

    R =[]
    for i in range(2):
        R.append(A[i],B[i],C[i])
    return R

CodePudding user response:

This seems like a job for np.stack, it can be used to do just that

result = np.stack([A, B, C], axis=2);

You can change the value of axis depending on how you want to merge them.

CodePudding user response:

One way to achieve this is as follows:

np.c_[A,B,C].reshape((-1,3,3)).transpose((0,2,1))

First, stack (as columns) the three arrays yielding an array of shape (1200,9). Then, reshape it to the desired shape of (1200,3,3) and lastly, transpose the last two dimensions so each column in the nested 2D array is from either A,B or C.

Example input:

A = np.array([[1,2,3],[4,5,6]])
B = np.array([[-1,-2,-3],[-4,-5,-6]])
C = np.array([[11,12,13],[14,15,16]])
np.c_[A,B,C].reshape((-1,3,3)).transpose((0,2,1))

Output:

array([[[ 1, -1, 11],
        [ 2, -2, 12],
        [ 3, -3, 13]],
       [[ 4, -4, 14],
        [ 5, -5, 15],
        [ 6, -6, 16]]])

CodePudding user response:

The other answers might already be enough for you make it work but here's a small function that does what you want (as I understand):

def new_mat(*arrs):
    
    combined =  np.concatenate([arrs])
    
    return combined[:,0,:].T
  • Related