将Matlab代码转换为Python时出现“无法理解数据类型”

b0zn9rqh  于 2022-12-04  发布在  Matlab
关注(0)|答案(1)|浏览(169)

I am trying to convert the following code from Trefethen's Spectral Methods in MATLAB to Python.

% p6.m - variable coefficient wave equation

% Grid, variable coefficient, and initial data:
  N = 128; h = 2*pi/N; x = h*(1:N); t = 0; dt = h/4;
  c = .2 + sin(x-1).^2;
  v = exp(-100*(x-1).^2); vold = exp(-100*(x-.2*dt-1).^2);

% Time-stepping by leap frog formula:
  tmax = 8; tplot = .15; clf, drawnow, set(gcf,'renderer','zbuffer')
  plotgap = round(tplot/dt); dt = tplot/plotgap;
  nplots = round(tmax/tplot);
  data = [v; zeros(nplots,N)]; tdata = t;
  for i = 1:nplots
    for n = 1:plotgap
      t = t+dt;
      v_hat = fft(v);
      w_hat = 1i*[0:N/2-1 0 -N/2+1:-1] .* v_hat;
      w = real(ifft(w_hat)); 
      vnew = vold - 2*dt*c.*w; vold = v; v = vnew;
    end
    data(i+1,:) = v; tdata = [tdata; t];
  end
  waterfall(x,tdata,data), view(10,70), colormap(1e-6*[1 1 1]);
  axis([0 2*pi 0 tmax 0 5]), ylabel t, zlabel u, grid off

For the most part it is going smoothly except for this line of code

data = [v; zeros(nplots,N)]

After reading how to convert between Numpy and Matlab here Link I tried to convert it by doing the following

data = np.array(v,zeros(nplots,N))

but I get this error

data = np.array(v,zeros(nplots,N));
 TypeError: data type not understood

Which I assume is because a numpy array has this structure

numpy.array(object,dtype=none)

I would appreciate any help with converting that line. Thank you in advance!

yb3bgrhw

yb3bgrhw1#

data = [v; zeros(nplots,N)]这是连接两个矩阵并将它们堆叠起来,注意numpy中的;,您可以使用numpy.concatenate((v, zeros((nplots,N))), axis = 0),其中axis是您要连接的轴,通过...

data = np.array(v,zeros(nplots,N));
TypeError: data type not understood

基本上,当您调用np.array时,第一个参数必须是可迭代对象、列表、元组,而第二个参数必须是类型,即“int”、“float32”“float32”等等...但是您将类型设置为zeros(nplots,N)numpy却抱怨它不是类型... numpy.zeros是相同的,第一个参数必须是元组,第二个参数必须是类型,很抱歉,我没有正确地包括()
它应该是data = numpy.concatenate((v, numpy.zeros((nplots,N))), axis = 0),假设您要使用double类型,这是标准类型。

相关问题