Reputation: 349
How do I compute the minimum sum of elements in a matrix python? for example:
z =
np.array([[1, 2, 3],
[3, 2, 5],
[2, 4, 4]])
The minimum sum of the element is : 1+2+2 = 5
I tried:
def calculate(a):
sum = 0
for i in range(len(a)):
sum += np.sum(a[i])
return sum
but it gives me 26 instead of 5
Upvotes: 0
Views: 1260
Reputation: 61325
So, you've z
as the following array. In NumPy, you've to understand axis
of the array: (please see this answer for a better mental image: very-basic-numpy-array-dimension-visualization ). So, the array here is 2D.
#----> axis: 1 #| a
array([[1, 2, 3], #| x
[3, 2, 5], #| i
[2, 4, 4]]) #| s
#v 0
So, we find minimum along axis 1
In [70]: np.min(z, axis=1)
Out[70]: array([1, 2, 2])
And since you also need sum, you call .sum()
on the resulting 1D array from the above step. Below is the code in a single line:
In [71]: np.min(z, axis=1).sum()
Out[71]: 5
A general rule of thumb would be to not use for
loops with NumPy arrays since that would be awfully slow (in terms of runtime).
Upvotes: 0
Reputation: 36604
You shouldn't use for loops to perform operations with Numpy arrays. Numpy exists to provide optimized alternatives to loops, and using loops kind of defeats that purpose. You can take the minimum value of each row (collapsing the first axis), then sum up the resulting three values:
np.sum(np.min(z, axis=1))
Out[61]: 5
Upvotes: 3
Reputation: 1396
You could apply function to find minimum value for each row and sum after that.
import numpy as np
z = np.array([[1, 2, 3],
[3, 2, 5],
[2, 4, 4]])
np.apply_along_axis(np.min,-1,z).sum()
How this works? First you define the function. Finding the minimum value, in this case. Second you define the axis you wish to find you values. See full description in documentation below. Lasly I run .sum() to sum up all the elements. For studying purposes I suggest running only
np.apply_along_axis(np.min,-1,z)
see more on Numpy documentation
Upvotes: 1
Reputation: 1672
You can use np.min()
:-
z = np.array([[1,2,3],[3,2,5],[2,4,4]])
res = sum(np.min(z, axis=1))
print(res)
Output:
5
Upvotes: 1
Reputation: 20669
You find np.min
over axis 1.
z = np.array([[1, 2, 3], [3, 2, 5], [2, 4, 4]])
z.min(1).sum()
# 5
Upvotes: 1
Reputation: 2992
You are adding the sum of the entire row to the sum, when you should be adding the minimum value. So just replace sum
with min
:
z = np.array([[1, 2, 3], [3, 2, 5], [2, 4, 4]])
def calculate(a):
sum = 0
for row in a:
sum += np.min(row)
return sum
print(calculate(z))
>>> 5
I also optimized your loop method to be clearer.
Upvotes: 1