首页 > 解决方案 > 有关带有方程和索引的输出数组的更多信息

问题描述

我有一个数学函数,其输出由两个变量定义,x并且y.

功能是e^(x^3 + y^2)

x我想为and计算 1 和某个定义的整数之间的每个可能的整数组合y,并将它们放在一个数组中,以便每个输出与对应的x值和y值索引对齐。所以像:

给定:

x = 3
y = 5

输出将是这样的数组:

f(1,1) f(1,2) f(1,3)
f(2,1) f(2,2) f(2,3)
f(3,1) f(3,2) f(3,3)
f(4,1) f(4,2) f(4,3)
f(5,1) f(5,2) f(5,3)

我觉得这是一个容易解决的问题,但我的知识有限。下面的代码是最好的描述。

import math 
import numpy as np

equation = math.exp(x**3 + y**2)

#start at 1, not zero
i = 1
j = 1

#i want an array output
output = []

#function
def shape_f (i,j):
    shape = []
    output.append(shape)
    while i < x + 1:
        while j < y +1: 
            return math.exp(i**3 + j**2)

#increase counter
i = i +1
j = j +1
print output

我最近得到了一个空白数组,但我也得到了一个值(int 而不是数组)

标签: pythonnumpyvectorization

解决方案


我不确定你是否有缩进错误,但看起来你从来没有对函数的输出做任何事情shape_f。您应该将方程定义为函数,而不是表达式赋值。然后,您可以创建一个函数来填充您所描述的列表列表。

import math

def equation(x, y):
    return math.exp(x**3 + y**2)

def make_matrix(x_max, y_max, x_min=1, y_min=1):
    out = []
    for i in range(x_min, x_max+1):
        row = []
        for j in range(y_min, y_max+1):
            row.append(equation(i, j))
        out.append(row)
    return out

matrix = make_matrix(3, 3)
matrix
# returns:
[[7.38905609893065, 148.4131591025766, 22026.465794806718],
 [8103.083927575384, 162754.79141900392, 24154952.7535753],
 [1446257064291.475, 29048849665247.426, 4311231547115195.0]]

推荐阅读