简体   繁体   English

计算每个网格网格点的值数组

[英]Computing an array of values for each meshgrid point

I have a function that depends on some parameters and which output is an array. 我有一个函数,它取决于某些参数,并且哪个输出是数组。 For example: 例如:

def my_func(xs,param1,param2,param3):
    values = xs**param1 + xs*param2**2 + param3*xs
    return values

where xs is an array with values. 其中xs是具有值的数组。 Suposse I also have a list of values for each of the parameters: 假定我也有每个参数的值列表:

xs = np.arange(0,10,1)
params1 = np.arange(5,10,1)
params2 = np.arange(1,30,1)
params3 = np.arange(1,20,1)

I would like to compute the output of my_func for each possible combination of params1, params2, and params3. 我想为params1,params2和params3的每种可能组合计算my_func的输出。 The idea is to be able to compute chi squares and perform bayesian analysis with the output. 这个想法是要能够计算卡方和对输出执行贝叶斯分析。 I know it can be done with nested for loops, but I was wondering if that could be done with mehsgrid. 我知道可以使用嵌套的for循环来完成,但是我想知道是否可以使用mehsgrid来完成。 I tried the following, but it breaks: 我尝试了以下操作,但会中断:

P1, P2, P3 = np.meshgrid(params1,params2,params3)
results = my_func(xs,P1,P2,P3)

      1 def my_func(xs,param1,param2,param3):
----> 2     values = xs**param1 + xs*param2**2 + param3*xs
      3 
      4 
      5 xs = np.arange(0,10,0.1)

      ValueError: operands could not be broadcast together with shapes (100,) (10,10,40) 

Any idea of how this can be done (if it can be done)? 关于如何做到这一点的任何想法(如果可以做到)?

Edit: The answer by @unutbu works, but no I have one extra question regarding the format of its output. 编辑: @unutbu的答案有效,但是不,我对其输出格式有一个额外的问题。 I have changed the parameters ranges so it can be easily explained. 我更改了参数范围,因此可以很容易地解释它。

After passing xs as a parameter for np.meshgrid , the shape of results is xs作为np.meshgrid的参数传递后, results的形状为

np.shape(results)
(5, 10, 29, 19)

Meaning that: axis0 is param1 , axis1 is xs , axis2 is param2 , and axis3 is param3 . 这意味着:axis0是param1 ,axis1是xs ,axis2是param2 ,而axis3是param3

Why is xs put in axis=1 in the output? 为什么将xs放在输出中的axis = 1中? I would expect the order to follow what passed to np.mesgrid , ie, xs,param1,param2, param3 . 我希望命令遵循传递给np.mesgrid ,即xs,param1,param2, param3

Edit2: EDIT2:

sorry, I have just discovered the "indexing" keyworkd for np.meshgrid. 抱歉,我刚刚发现了np.meshgrid的“索引”键。 In case anyone needs the indexing as I was planning to use it, use np.meshgrig(arguments,indexing='ij') . 如果有人在我打算使用索引时需要索引,请使用np.meshgrig(arguments,indexing='ij')

Pass xs also as an argument to np.meshgrid : xs也作为参数传递给np.meshgrid

import numpy as np

def my_func(xs,param1,param2,param3):
    values = xs**param1 + xs*param2**2 + param3*xs
    return values

xs = np.arange(0,10,0.1)
params1 = np.arange(1,2,0.1)
params2 = np.arange(1,2,0.1)
params3 = np.arange(1,5,0.1)

X, P1, P2, P3 = np.meshgrid(xs, params1, params2, params3, sparse=True, indexing='ij')
my_func(X, P1, P2, P3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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