matrix edition

5

I am writing a program that I read a matrix and if the value of the element is less than a value rewrite it as zero and if it is greater than the value, leave it as such. I do this:

lis=open('ej.txt','r')
A=lis.read()
A=np.genfromtxt(StringIO(A))
print A
for i in A:
    if A.all() <= 2:
       A = A*0.
    elif A > 2:
       A =A*1
A=A
print A

and the output is this, the first the original input and the second the output of the program:

[[ 0.    0.1   0.2   0.3   0.45]
 [ 1.2   1.4   1.6   2.8   3.92]
 [ 2.1   1.8   2.4   2.2   4.7 ]
 [ 3.2   3.4   5.1   6.2   5.22]]

[[ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]]

The program does not consider the second condition. Could someone help me?

    
asked by anonimo 23.08.2016 в 02:05
source

1 answer

6

Using the indexed fancy , it can be indexed with a Boolean masquerade:

Code

import numpy as np

A = np.array([[ 0.,    0.1,   0.2,   0.3,   0.45],
              [ 1.2,   1.4,   1.6,   2.8,   3.92],
              [ 2.1,   1.8,   2.4,   2.2,   4.7 ],
              [ 3.2,   3.4,   5.1,   6.2,   5.22]])

A[A<=2] = 0
print A

Result

[[ 0.    0.    0.    0.    0.  ]
 [ 0.    0.    0.    2.8   3.92]
 [ 2.1   0.    2.4   2.2   4.7 ]
 [ 3.2   3.4   5.1   6.2   5.22]]

Demo at ideone.com

    
answered by 23.08.2016 в 04:08