Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to plot two variable function, calculating function loop gives wrong shape

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading