Home > Back-end >  converting Matlab to python code : IndexError: index -1 is out of bounds for axis 0 with size 0
converting Matlab to python code : IndexError: index -1 is out of bounds for axis 0 with size 0

Time:06-27

Converting Matlab code to python . IndexError: index -1 is out of bounds for axis 0 with size 0 Matlab

for i = 1:N
            for j=1:N
                s = zeros(L2,L2);
                sX = zeros(L2,L2);
                sSS= Y((i-1)*L2 1:i*L2,(j-1)*L2 1:j*L2);
                BI{i,j} = sSS;
                

Python

for i in range(N):
        for j in range(N):
            s = zeros(N, N);
            sX = zeros(N,N);
            sSS =Y[arange(dot((i - 1),L2)   1,dot(i,L2)),arange(dot((j - 1),L2)   1,dot(j,L2))]
            BI [i,j] = sSS
           

IndexError: index -1 is out of bounds for axis 0 with size 0. According to the line of BI [i,j] = sSS. The index difference between matlab and python. Matlab starts index 1 and Python starts index 0.

CodePudding user response:

MATLAB indices (i-1)*L2 1:i*L2,(j-1)*L2 1:j*L2 are simply translated into Python's as this i*L2:(i 1)*L2, j*L2:(j 1)*L2. You should initialize BI outside the loops and s, sX does nothing inside the loops. Also, Y is not defined outside the loops.

Note, you shouldn't import everything from numpy like this, it should be import numpy as np and use np.func(..) wherever you want. BI was defined as a list which is closer to a cell array in MATLAB.

from numpy import *    # not recommended to import everything

N = L2 = 5
Y = random.rand(100,100)
BI = []
for i in range(N):
    BI.append([])
    for j in range(N):
        # s = zeros((L2,L2))  # does nothing
        # sX = zeros((L2,L2)) # does nothing
        sSS = Y[i*L2:(i 1)*L2, j*L2:(j 1)*L2]
        BI[i].append(sSS)
  • Related