Home > Net >  How can one define a function ony a numpy matrix of vectors, that returns a value for every vector?
How can one define a function ony a numpy matrix of vectors, that returns a value for every vector?

Time:08-15

I have a 3-dimensional numpy array:

import numpy as np
threeDimArray = np.arange(24).reshape((3, 2, 4))
print(threeDimArray)

The print-statement returns:

[[[ 0  1  2  3]
  [ 4  5  6  7]]
 [[ 8  9 10 11]
  [12 13 14 15]]
 [[16 17 18 19]
  [20 21 22 23]]]

I define a function that is supposed to calculate the sum for every vector on the array and replace these vectors with these calculated sums:

def myOperation():
    img_temp=threeDimArray.copy()
    nrows=img_temp.shape[0]
    ncolumns = img_temp.shape[1]
    for j in range(ncolumns):
        for i in range(nrows):
            img_temp[i][j]=sum(img_temp[i][j])
    return(img_temp)

The function is intended to return this:

[[6,22],
  [38,54],
  [70,86]]

Instead it returns this:

[[[ 6,  6,  6,  6],
        [22, 22, 22, 22]],
       [[38, 38, 38, 38],
        [54, 54, 54, 54]],
       [[70, 70, 70, 70],
        [86, 86, 86, 86]]]
  1. Why does it do this?
  2. How can I change the function to return what I described?

CodePudding user response:

In [133]: arr = np.arange(24).reshape(3,2,4)
In [134]: arr
Out[134]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [12, 13, 14, 15]],

       [[16, 17, 18, 19],
        [20, 21, 22, 23]]])

With a numpy array, you don't have to iterate (in python). Let the sum method do it - with axis to specify how:

In [135]: arr.sum(axis=-1)
Out[135]: 
array([[ 6, 22],
       [38, 54],
       [70, 86]])

In your code you make img_temp to be the same shape as the source:

In [138]: def myOperation(arr):
     ...:     img_temp=arr.copy()
     ...:     nrows=img_temp.shape[0]
     ...:     ncolumns = img_temp.shape[1]
     ...:     for j in range(ncolumns):
     ...:         for i in range(nrows):
     ...:             img_temp[i][j]=sum(img_temp[i][j])
     ...:     return(img_temp)
     ...: 
In [139]: myOperation(arr)
Out[139]: 
array([[[ 6,  6,  6,  6],
        [22, 22, 22, 22]],

       [[38, 38, 38, 38],
        [54, 54, 54, 54]],

       [[70, 70, 70, 70],
        [86, 86, 86, 86]]])

Just select one column on the last dimension, and you get what you want:

In [140]: myOperation(arr)[:,:,0]
Out[140]: 
array([[ 6, 22],
       [38, 54],
       [70, 86]])

Here's a version of your function that does what you want:

In [143]: def myOperation(arr):
     ...:     nrows,ncolumns = arr.shape[:2]
     ...:     img_temp=np.zeros((nrows,ncolumns), arr.dtype)
     ...:     for j in range(ncolumns):
     ...:         for i in range(nrows):
     ...:             img_temp[i,j]=sum(arr[i,j])
     ...:     return(img_temp)
     ...: 
In [144]: myOperation(arr)
Out[144]: 
array([[ 6, 22],
       [38, 54],
       [70, 86]])
  • Related