简体   繁体   中英

Assign rows of a Matrix to a new Matrix

I have a matrix named v1 and I want to create another matrix named matriz1 that has only the items of the length of v1*2/3

v1=np.matrix('1,2;3,4;2,6;4,5')
distancia=len(v1)
distancia=distancia*2/3
matriz1=np.matrix
print(distancia)
k=0
print()
print()
print('matriz1')
for k in range(0,(int(distancia))):
    matriz1[k]=v1[k]
    k=k+1
print(matriz1)

The error is: TypeError

      Traceback (most recent call last)
<ipython-input-206-1ed800e332a1> in <module>()
     77 print('matriz1')
     78 for k in range(0,(int(distancia))):
---> 79     matriz1[k]=v1[k]
     80     k=k+1
     81 print(matriz1)

TypeError: 'type' object does not support item assignment

I know I am not defining a length for that matrix. What can I do to solve it?

You don't create a new matrix, but just give np.matrix another name matriz1 .

For numpy, you don't need loops, just use index slicing:

v1 = np.matrix('1,2;3,4;2,6;4,5')
distancia = len(v1) * 2 // 3
matriz1 = v1[:distancia].copy()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM