我有两个矩阵
fi = [[f1], Nij = [[N11 N12 .......N1n],
[f2], [N21 N22 .......N2n],
. ...
. ...
[fn]] [Nn1 Nn2 .......Nnn]]
我想乘:
f1 to each element of the 1st row,
f2 to each element of the 2nd row,
等等.
即我想要 Xij = fi*Nij
其中 fi 是列矩阵,Xij &Nij 是 nxn 矩阵.
I.e. I want Xij = fi*Nij
where fi is a column matrix and Xij & Nij is nxn matrix.
我尝试过使用
import numpy as np
fi = np.linspace(1,5, num =5)
fi = np.asmatrix(fi)
def Xij(ai):
Nij = np.ones((5,5))
for i in range(len(fi)):
for j in range(len(fi)):
Xij[i,j] = ai[i] * Nij[i,j]
return Xij
Zij = Xij(fi)
它给了我这个错误 TypeError: 'function' object does not support item assignment
为什么?我该如何解决这个问题?
Why? and how do I solve this?
你的问题就在这里:
Xij[i,j] = ai[i] * Nij[i,j]
你命名了一个变量Xij
,同时也是一个函数.此外,当您命名函数时,它会覆盖变量.
You named a variable Xij
, but also a function. Furthermore, when you named the function, it overwrote the variable.
因此,当您尝试对函数进行索引并为其分配项目时,会生成错误,因为您无法对函数执行此操作.下面是一个例子:
Because of this, when you try to index the function and assign its items, an error is generated because you can't do that on the function. Below is an example:
>>> def test(): print "Hi"
...
>>> test[1] = "yo!"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'function' object does not support item assignment
>>>
这个错误看起来很眼熟吗?它与您生成的相同,因为我所做的正是您所做的.
Does that error look familiar? It is the same one you generated because I did exactly what you did.
要解决此问题,请将函数名称更改为 Xij
以外的名称.这样做会使 Xij
等于矩阵,这将支持索引和项分配.
To fix this problem, change the name of you function to something other than Xij
. Doing so will make Xij
equal the matrice, which will support indexing and item assignment.
这篇关于“TypeError: 'function' 对象不支持项目分配"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!