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
.
JavaScript
x
8
1
import numpy as np
2
3
A = np.matrix(np.arange(12).reshape((3,4)))
4
MAX, MIN = A.max(), A.min()
5
B = np.matrix((A - MIN)/(MAX - MIN))
6
print(A)
7
print(B)
8
Output:
JavaScript
1
7
1
[[ 0 1 2 3]
2
[ 4 5 6 7]
3
[ 8 9 10 11]]
4
[[0. 0.09090909 0.18181818 0.27272727]
5
[0.36363636 0.45454545 0.54545455 0.63636364]
6
[0.72727273 0.81818182 0.90909091 1. ]]
7