Daniel
Daniel

Reputation: 3

How to fix dimension problem in Python shape of x and y differ

My code runs and returns the value of K as expected but the graph does not display w, due to an issue with dimensions. I'd be thankful for any help.

import numpy as np
import pylab as pl

k = np.linspace(0,0.1,1000)
h = 50
g = 9.81
w = 0.5*(np.ones(len(k)))

w = np.sqrt((g*k)*np.tanh(h*k))

k = max(k[w<=0.5])
print("The wave number, k = %.4f" % k)

pl.figure()
pl.plot(k, w)
pl.show()

However, plotting returns the following error:

x and y must have same first dimension, but have shapes (1,) and (1000,)

Upvotes: 0

Views: 463

Answers (1)

CAPSLOCK
CAPSLOCK

Reputation: 6483

This will do:

import numpy as np
import pylab as pl

k = np.linspace(0,0.1,1000)
h = 50
g = 9.81
w = 0.5*(np.ones(len(k)))

w = np.sqrt((g*k)*np.tanh(h*k))

kmax = max(k[w<=0.5])
print("The wave number, k = %.4f" % kmax)

pl.figure()
pl.plot(k, w)
pl.show()

output

OP also mentioned in a comment that he would like to mark the point kmax on the plot.
This can be done as follows:

import numpy as np
import pylab as pl

k = np.linspace(0,0.1,1000)
h = 50
g = 9.81
w = 0.5*(np.ones(len(k)))

w = np.sqrt((g*k)*np.tanh(h*k))

kmax = max(k[w<=0.5])
print("The wave number, k = %.4f" % kmax)

pl.figure()
pl.plot(k, w)
pl.plot(kmax,w[k==kmax],'.',color='r')
pl.show()

output2

Upvotes: 1

Related Questions