英文:
Trying to plot two variable function, calculating function loop gives wrong shape
问题
以下是代码的翻译部分:
我有一个名为 ```f``` 的函数,它是一个带有两个参数 ```x``` 和 ```y``` 的复杂积分。我想在这个参数空间中制作轮廓图(即在一些数组 ```X``` 和 ```Y``` 上),所以我使用循环遍历这两个参数。
我的代码如下:
```python
def Z_values(X, Y, f):
matrix = []
columns = []
for x in X:
for y in Y:
a = f(x, y)
columns.append(a)
matrix.append(columns)
columns.clear()
return matrix
plt.contour(X, Y, Z_values(X, Y, f))
plt.show()
我得到以下错误:
TypeError: 输入 z 必须至少是一个形状为 (2, 2) 的数组,但形状为 (4, 0))
我不明白我在循环中做错了什么。有什么问题吗?
编辑:错误的复制粘贴错误。
<details>
<summary>英文:</summary>
I have some function ```f```, which is some compliciated integral taking two parameters ```x``` and ```y``` . I want to make contour plot in this parameter space (i.e. over some arrays ```X``` and ```Y```), so I use loops over those two paremeters.
My code looks like this:
def Z_values(X,Y,f):
matrix=[]
columns=[]
for x in X:
for y in Y:
a=f(x,y)
columns.append(a)
matrix.append(columns)
columns.clear()
return matrix
plt.contour(X,Y,Z_values(X,Y,f))
plt.show()
I get following error:
```TypeError: Input z must be at least a (2, 2) shaped array, but has shape (4, 0))```
I don't understand what I do wrong in the loop. What is wrong?
Edit: wrong copypasted error.
</details>
# 答案1
**得分**: 1
不能在循环外创建`columns`,然后在循环内清除它。在这种情况下,`matrix`实际上包含对相同`column`的引用,而且它会一遍又一遍地被清空。因此,`Z_values`函数返回一个空列表的列表。
以下是已更正的代码:
```python
def Z_values(X, Y, f):
matrix = []
for x in X:
columns = []
for y in Y:
a = f(x, y)
columns.append(a)
matrix.append(columns)
return matrix
plt.contour(X, Y, Z_values(X, Y, lambda x, y: np.exp(x**2 + y**2)))
plt.show()
我建议您学习一些基本的C/C++编程知识,以理解引用/指针的概念以及它们与数据实际存储在内存地址相关的方式。这将帮助您避免这种类型的错误。
英文:
You cannot create columns
outside the loop and clear it in the loop. In such case the matrix
actually contains the reference points to the same column
and it's getting cleared again and again. So the function Z_values
returns list of empty list.
Corrected code as below:
def Z_values(X,Y,f):
matrix=[]
for x in X:
columns=[]
for y in Y:
a=f(x,y)
columns.append(a)
matrix.append(columns)
return matrix
plt.contour(X,Y,Z_values(X,Y,lambda x,y: np.exp(x**2+y**2)))
plt.show()
I would suggest you to learn some basic C/C++ programming to understand the concept of reference/pointer and how they are related to memory addresses where the data are actually stored. This will help you avoid this kind of mistake.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论