尝试绘制两个变量函数,计算函数循环会得到错误的形状。

huangapple go评论65阅读模式
英文:

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&#39;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.

huangapple
  • 本文由 发表于 2023年2月26日 19:15:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75571602.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定