0

I'm working with numpy in Python3, I have 512X512 matrix, I need to read every value and send to the function - the function will do some calculation and will be return 3 values- now I need to add this 3 values in separate matrix- by the way my matrix will be 512X512X512.

for example : main matrix

 a=[1,2,3,4,5…23] [23,24,33,….23]…(512)….[11,22,33,44,55,…66]

I want to pickup every element (e.g.: 1) then calculate in function and return 3 values- let’s call returned values are: a1,a2,a3 then I have add in separate matrix like in here:

 tempA=[a1,…] 
 tempB=[a2,…]
 tempC=[a3,…]

How I can do it with numpy in Python?

Big Data
  • 15
  • 4
  • did you try anything? the community will jump in quicker if you provide any attempt of yours – transient_loop Mar 18 '17 at 01:26
  • 1
    Looks more like you'll produce a (512,512,3) array. How general is the function? Does it only work with a scalar input (as opposed to a row of the (512,512)? Give a small example, with an actual function and a smaller array (e.g. 10x10). – hpaulj Mar 18 '17 at 01:45
  • can you elaborate on what the function does? depending on its complexity, it's possible that you avoid the need to `vectorize` – Crispin Mar 18 '17 at 10:41

1 Answers1

1

Since I was just playing with np.vectorize in How can I map python callable over numpy array in both elegant and efficient way?, I can apply it to your case:

In [462]: def foo(val):
     ...:     return val, val*2, val*3
     ...: 
In [463]: fv = np.vectorize(foo, otypes=[int,int,int])

One otypes value for each of the 3 returned values from foo.

In [464]: X = np.arange(12).reshape(3,4)
In [465]: X
Out[465]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

The vectorized function returns a tuple of arrays, which we can unpack and/or regroup in a 3d array:

In [466]: tmp1, tmp2, tmp3 = fv(X)
In [467]: tmp1
Out[467]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [468]: tmp2
Out[468]: 
array([[ 0,  2,  4,  6],
       [ 8, 10, 12, 14],
       [16, 18, 20, 22]])
In [469]: tmp3
Out[469]: 
array([[ 0,  3,  6,  9],
       [12, 15, 18, 21],
       [24, 27, 30, 33]])
In [470]: np.array((tmp1,tmp2,tmp3))
Out[470]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[ 0,  2,  4,  6],
        [ 8, 10, 12, 14],
        [16, 18, 20, 22]],

       [[ 0,  3,  6,  9],
        [12, 15, 18, 21],
        [24, 27, 30, 33]]])
Community
  • 1
  • 1
hpaulj
  • 221,503
  • 14
  • 230
  • 353