1

如何将地址和公式分配给数组?

例如

import numpy as np
import math
from numpy import matrix
y = np.matrix( [y,y,y],[ -2,0,3]])

我想打电话y(i=0 j) for j in range(3)或分配它f(x)=2x+5 for x in range(3)

4

1 回答 1

0

你不能从第一行开始,因为y在你使用它之前没有定义:

np.matrix([y, y, y], [-2, 0, 3]])  # interpreter says "what is y?"

因此,请从您的功能开始。如果你想f(x) = 2*x + 5在多个值上调用你的函数,你必须先定义它:

def f(x):
    return 2*x + 5

然后你可以一次对所有值调用它,假设你为输入创建了一个数组:

xs = np.arange(3)  # -> array([0, 1, 2])
f(xs)              # -> array([5, 7, 9])

现在,您可以这样构建y

y = np.matrix([f(xs), [-2, 0, 3]])
# matrix([[ 5,  7,  9],
#         [-2,  0,  3]])

或者,您可以先构建y,然后再填充:

y = np.matrix([[0, 0, 0], [-2, 0, 3]])
y[0, :] = f(xs)  # `0` means first row, `:` means all columns
print y
# matrix([[ 5,  7,  9],
#         [-2,  0,  3]])
于 2013-11-09T20:12:37.187 回答