vonNeumann
vonNeumann

Reputation: 21

Calculate max and min of three matrices

I had three matrices, and I wanted to calculate the minimum and maximum of Rl and first columns of Ex1 and Ex2. I save the minimum in Il and maximum in Ih. When I evaluate the maximum, the matrix Il is changed to Ih, don't know why. Also, the calculation of the maximum is not actually maximum. The code is given below along with observed and expected outputs. One would expect the first and third print statement to give the same output but it is not doing so.

import numpy as np

Rl = np.matrix([[70,15,10,15,65]]).transpose()
Ex1 = np.matrix([[20,10,40,2,40] ,[ 55,22,50,10,60], 
[80,40,75,25,80]]).transpose()
Ex2 = np.matrix([[30,20,30,10,50],[50,30,50,20,60], 
[60,40,70,30,70]]).transpose()
Il = np.minimum(Rl[:,0],Ex1[:,0],Ex2[:,0])
print("Il =\n {}\n".format(Il))
Ih = np.maximum(Rl[:,0],Ex1[:,0],Ex2[:,0])
print("Ih =\n {}\n".format(Ih))
print("Il =\n {}\n".format(Il))

Actual results

Il =
 [[20]
 [10]
 [10]
 [ 2]
 [40]]

Ih =
 [[70]
 [15]
 [40]
 [15]
 [65]]

Il =
 [[70]
 [15]
 [40]
 [15]
 [65]]

Expected results

Il =
 [[20]
 [10]
 [10]
 [ 2]
 [40]]

Ih =
 [[70]
 [20]
 [40]
 [15]
 [65]]

Il =
 [[20]
 [10]
 [10]
 [ 2]
 [40]]

Upvotes: 2

Views: 232

Answers (2)

benvc
benvc

Reputation: 15120

Since np.minimum() and np.maximum() only compare 2 arrays at a time, you could nest them in order to compare 3. For example:

import numpy as np

a = np.matrix([[70,15,10,15,65]]).transpose()
b = np.matrix([[20,10,40,2,40],[55,22,50,10,60],[80,40,75,25,80]]).transpose()
c = np.matrix([[30,20,30,10,50],[50,30,50,20,60],[60,40,70,30,70]]).transpose()

abc_min = np.minimum(np.minimum(a[:,0], b[:,0]), c[:,0])
abc_max = np.maximum(np.maximum(a[:,0], b[:,0]), c[:,0])

print("abc_min =\n {}\n".format(abc_min))
print("abc_max =\n {}\n".format(abc_max))
# OUTPUT
# abc_min =
#  [[20]
#  [10]
#  [10]
#  [ 2]
#  [40]]
# 
# abc_max =
#  [[70]
#  [20]
#  [40]
#  [15]
#  [65]]

Upvotes: 0

jasonharper
jasonharper

Reputation: 9597

Numpy's .minimum() and .maximum() simply don't work with more than two arrays. That third parameter is being interpreted as the output array, so you're overwriting Ex2 and printing its modified contents each time.

Upvotes: 1

Related Questions