[SciPy-User] [SciPy-user] ValueError: arrays must have same number of dimensions

Tony Yu tsyu80@gmail....
Thu Jun 28 11:06:11 CDT 2012


On Thu, Jun 28, 2012 at 11:48 AM, Jorge E. ´Sanchez Sanchez <
hnry2k@hotmail.com> wrote:

>  Hi,
>
> it seems to me that you don't know that loops in python end before the
> last index value of the loop,
> you just need to do something like:
>  Np1 = N+1
> for j in range (1, Np1):
>
> HTH
> Best Regards
> Jorge
>

>
> > Date: Thu, 28 Jun 2012 08:32:47 -0700
> > From: surfcast23@gmail.com
> > To: scipy-user@scipy.org
> > Subject: [SciPy-User] [SciPy-user] ValueError: arrays must have same
> number of dimensions
>
> >
> >
> > Hi I am trying to translate a Matlab code from Trefethen's Spectral
> Methods
> > in MATLAB to Python. I am running into a problem with numpy.concatenate
> > wanting the arrays to have the same number of dimensions.
> > Here is part of the Matlab code that I am rewriting
> >
> >
> > N = 512; h = 2*pi/N; x = h*(1:N); t = 0; dt = h/4;
> > a = .1;
> > c = a + sin (x-1).^2;
> > v = exp(-100*(x-1).^2); vold = exp(-100*(x-a*dt-1).^2);
> >
> > column = [0 .5*(-1).^(1:N-1).*cot((1:N-1)*h/2)];
> > D = toeplitz(column,-column);
> >
> > % Time-stepping by leap frog formula:
> > tmax = 15; 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;
> >
> >
> > What I am trying in Python
> >
> > for j in range(1,N):
>

[snip]

You actually don't need to loop. Your original matlab code translates
fairly naturally into numpy code: the main difference being the
substitution of `np.arange(N) + 1` for `[1:N]`, where `np.arange(N)` gives
values from 0 to N - 1, as Jorge suggests (although it's not specific to
loops).

Here's a rough translation (not tested against matlab output, so I could
have made some errors in the translation).

Cheers,
-Tony

#~~~ code
import numpy as np
from scipy.linalg import toeplitz
from scipy.special import cotdg

N = 512
h = 2 * np.pi/N
x = h * (np.arange(N) + 1)
t = 0
dt = h / 4
a = .1
c = a + np.sin(x - 1)**2
v = np.exp(-100 * (x - 1)**2)
vold = np.exp(-100 * (x - a*dt - 1)**2)

i = np.arange(1, N)
column = np.hstack([0, .5 * (-1**i) * cotdg(i * h/2)])
D = toeplitz(column, -column)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20120628/9b87f57a/attachment.html 


More information about the SciPy-User mailing list