I have a matrix named A, and I want to create a new matrix named B, where each element value is generated by this formula:
B[i][j] = (A[i][j] - MIN) / (MAX - MIN)
, where
i
is the line indexj
is the column index.MIN
is the minimum fromA
MAX
is the value with highest value fromA
.
I tried a for loop but I want to increase efficiency, I want to use numpy function but I don’t know which function I have to use and how to use this function, with my problem.
Advertisement
Answer
I’m not sure whether the MIN
&MAX
are standing for
- the
MIN
&MAX
value of the column/row fromA
, or - the
MIN
&MAX
value of the entire matrix(A
).
Plz leave a comment if I’m misunderstanding and here’s the solution for second meaning of MIN
&MAX
.
import numpy as np A = np.matrix(np.arange(12).reshape((3,4))) MAX, MIN = A.max(), A.min() B = np.matrix((A - MIN)/(MAX - MIN)) print(A) print(B)
Output:
[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[0. 0.09090909 0.18181818 0.27272727] [0.36363636 0.45454545 0.54545455 0.63636364] [0.72727273 0.81818182 0.90909091 1. ]]