简体   繁体   中英

Python: obtain multidimensional matrix as results from a function

I have a multi-inputs function, say:

def bla(a, b):
    f = a + b
    return f

When I do something like

import numpy as np
bla(np.asarray([0.2,0.4]), np.asarray([2,4]))

The result is:

array([ 2.2,  4.4])

However, I want bla to be applied to each possible pair of my inputs( bla(0.2, 2) , bla(0.2, 4) , bla(0.4, 2) , bla(0.4, 4) ) and obtain the final result as a 2-D matrix. In this example, I want the result to be:

array([[2.2, 4.2],
[2.4, 4.4]
])

How can I do this? My original problem is that I have a function with three variables and one output, then I want to call the function by entering vectors for each variable so that I obtain a 3-D matrix as a result

Not sure if you want to do this without modifying bla() , but for your example at least that's where the change must be:

def bla(a, b):
    return np.asarray(a+n for n in b)

This operates on array a with each element of b , and builds an array with the results. Your example looks a little random (how did you get those .3 fractional parts?), but I'm guessing this is what you're trying to get at.

Provided your function bla can accept arrays instead of scalars, you could use meshgrid to prepare the inputs so that bla(A, B) returns the desired output:

import numpy as np
def bla(a, b):
    f = a + b
    return f

A, B = np.meshgrid([0.2,0.4], [2,4], sparse=True)
bla(A, B)

yields

array([[ 2.2,  2.4],
       [ 4.2,  4.4]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM