Search code examples
pythonlistnumpymatrixeigenvalue

How to create matrix from set of lists which contains more than 4 values?


I have set of lists (i.e. list x , list y, list z), e.g.

x = ['41.95915452', '41.96333025', '41.98135503', '41.95096716', '41.96504172', '41.96526867', '41.98068483', '41.98117072', '41.98059828', '41.95915452', '41.96333025', '41.98135503', '41.95096716']

y = ['12.60718918', '12.62725589', '12.6201431', '12.60017199', '12.62774075', '12.62800706', '12.62812394', '12.6278259', '12.62810614', '12.60718918', '12.62725589', '12.6201431', '12.60017199']

z = ['9.215398066', '8.249650758', '8.791595671', '8.246394455', '9.27132698', '5.667547722', '7.783268126', '9.471492129', '9.668210684', '9.215398066', '8.249650758', '8.791595671', '8.246394455']

There are such around 800 lists. I have to create a 3*3 matrix from the each of the lists x, y and z such that [x1, y1, z1], one of its row should be like ['41.95915452', '12.60718918', '9.215398066' ] and list must contain at least than 4 entries.

My code :

for i in np.arange(41.70, 42.10, 0.05):
    #print(round(i,2), end=', ')
    for j in np.arange(12.30, 12.80, 0.05):
    #   print(round(j,2), end=', ')
        for k in np.arange(0,26,5):
            #print("\n")
            #print(round(i,2),round(j,2),k, end=', ')
            xmax = round(i+0.05,2)
            ymax = round(j+ 0.05,2)
            zmax = round(k+5,2)
            #print("Voxel",xmax,ymax,zmax)
            v = []
            x1 = []
            y1 = []
            z1 = []
            count = 0;
            with open('a.csv') as csvfile:
                plots = csv.reader(csvfile,delimiter=',')
                for rows in plots:
                    if(float(rows[0]) >= i and float(rows[0])<= xmax and float(rows[1]) >=j and float(rows[1])<=ymax and float(rows[2])>=k and float(rows[2])<=zmax):
                        #print("points", float(rows[0]),float(rows[1]),float(rows[2]))

                        x1.append(rows[0])
                        y1.append(rows[1])
                        z1.append(rows[2])
                        count= count+1
                #f = open("demofile2.txt", "a")
                #f.write(str(i)+","+str(j)+","+str(k)+","+str(count)+"\n")
                #f.write(text)
                #f.close()
                #print(count)
                if(count > 3):
                    v1 = [i,j,k]
                    v.append(v1)
                    print(v)
                    print(x1)
                    print(y1)
                    print(z1)
                    print("\n")

Solution

  • you can use np.c_ to concatenate along axis and slice the matrix.

    res = np.c_[x,y,z][:3,:3]
    

    output

    array([['41.95915452', '12.60718918', '9.215398066'],
           ['41.96333025', '12.62725589', '8.249650758'],
           ['41.98135503', '12.6201431', '8.791595671']], dtype='<U11')