輸入陣列為 x,尺寸為 (1 x 3),輸出陣列為 3 x 3(輸入列 x 輸入列)。輸出陣列的對角線是值^2。如果 row != column,則公式為每個值的 x(row) x(col)。目前為 1 x 3,但應假定各種尺寸作為輸入。不能使用'def'。當前代碼不起作用,您會推薦什么?
x = np.array([[0, 5, 10]])
output array formulas =
[[i^2, x(row) x(col), x(row) x(col)]
[x(row) x(col), i^2, x(row) x(col)]
[x(row) x(col), x(row) x(col), i^2]]
# where row and column refer to the output matrix row, column. For example, the value in (1,2) is x(1) x(2)= 5
ideal output =
[[0 5 10]
[5 25 15]
[10 15 100]]
嘗試的代碼:
x = np.array([[0, 5, 10]])
r, c = np.shape(x)
results = np.zeros((c, c))
g[range(c), range(c)] = x**2
for i in x:
for j in i:
results[i,j] = x[i] x[j]
uj5u.com熱心網友回復:
學習使用 numpy 方法和廣播:
>>> x
array([[ 0, 5, 10]])
>>> x.T
array([[ 0],
[ 5],
[10]])
>>> x.T x
array([[ 0, 5, 10],
[ 5, 10, 15],
[10, 15, 20]])
>>> result = x.T x
>>> result
array([[ 0, 5, 10],
[ 5, 10, 15],
[10, 15, 20]])
然后這個方便的內置:
>>> np.fill_diagonal(result, x**2)
>>> result
array([[ 0, 5, 10],
[ 5, 25, 15],
[ 10, 15, 100]])
可以更換 results[range(c), range(c)] = x**2
uj5u.com熱心網友回復:
試試這個:
x.repeat(x.shape[1], axis=0)
x = x x.T
x[np.arange(len(x)),np.arange(len(x))] = (np.diag(x)/2)**2
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/420315.html
標籤:
上一篇:Numpy線與圓相交
