0

I have a matrix:

>    A[-1 0 1 0.5] 
>    [-0.2 0.8 1 -1] 
>     [0.4 0.8 1 -0.1] 
>     [-0.6 0.4 -1 1]

I want to extract a sub matrix from this.. so what I want the program to do is to make a matrix to preserve the signs... like so:

B[-1 +1 +1 +1]
[-1 +1 +1 -1]
[+1 +1 +1 -1]
[-1 +1 -1 +1]

and a matrix C which contains the element values

    C[1 0 1 0.5] 
    [0.2 0.8 1 1] 
     [0.4 0.8 1 0.1] 
     [0.6 0.4 1 1]

So when B and C are multiplied together, they make up matrix A.

hsayya
  • 131
  • 1
  • 10
  • please add the code you wrote to solve the above problem – Polaris000 Feb 02 '19 at 05:54
  • I haven't used a code yet.. I was thinking of using a for loop to loop each element and check the sign to put into a new matrix. but I was wondering if there is an easier way @Polaris000 – hsayya Feb 02 '19 at 05:55

3 Answers3

1

Make A into numpy array and use numpy.sign function. It’s easier since numpy does the loop for you.

import numpy
A=numpy.array([[-1,0,1,0.5],[-0.2 0.8 -1, 1],...])
B=numpy.sign(A)
C=A*B
Tim
  • 3,178
  • 1
  • 13
  • 26
0

You could use the absolute and sign methods from numpy.

import numpy as np

a = np.array([[-1, 0, 1, 0.5], [-0.2, 0.8, 1, -1], [0.4, 0.8, 1, -0.1], [-0.6, 0.4, -1, 1]])
b = np.sign(a)
c = np.absolute(a)

So b is:

array([[-1.,  0.,  1.,  1.],
       [-1.,  1.,  1., -1.],
       [ 1.,  1.,  1., -1.],
       [-1.,  1., -1.,  1.]])

and c is:

array([[1. , 0. , 1. , 0.5],
       [0.2, 0.8, 1. , 1. ],
       [0.4, 0.8, 1. , 0.1],
       [0.6, 0.4, 1. , 1. ]])

The only difference here is that the sign for element 0 is considered to be 0 and not +1 like you want.
Edit:
As mentioned in a helpful comment, to get the output for matrix b as you expect(with the sign of 0 being +1), you can do this:

b = -2 * np.signbit(a) + 1
Polaris000
  • 938
  • 1
  • 11
  • 24
0

Use numpy's sign and abs function like below

import numpy as np
A=np.array([[-1,0,1,0.5],[-0.2,0.8,1,-1], [0.4,0.8,1,-0.1], [-0.6,0.4,-1,1]])
B=np.sign(A)
C=np.abs(A)
print(B*C == A)
xashru
  • 3,400
  • 2
  • 17
  • 30