Home > database >  Modify the elements of a list inside a for loop (Python equivalent of Matlab code with a nested loop
Modify the elements of a list inside a for loop (Python equivalent of Matlab code with a nested loop

Time:01-19

I have the following Matlab code (adopted from Programming and Numerical Methods in MATLAB by Otto&Denier, page 75)

clear all
p = input('Enter the power you require: ');

points = p 2;
n = 1:points;
for N = n
     sums(N) = 0;
    for j = 1:N
        sums(N) = sums(N) j^p;
    end
end

The output for 3 as the given value of p is the following list

>> sums
sums =
       1              9             36            100            225 

I have written the following Python code (maybe not the most 'Pythonic way') trying to follow as much as possible Matlab instructions.

p = int(input('Enter the power you require: '))

points = p 2
n = range(points)
for N in range(1, len(n) 1):
    sums = [0]*N
    for index, item in list(enumerate(sums)):
        sums[index] = item index**p

Nevertheless the output is not same list. I have tried to replace the inner loop with

for j in range(1,N 1):
    sums[N] = sums[N] j**p

but this results to an index error message. Thanks in advance for any suggestions.

CodePudding user response:

This might be due to the index difference. In Python, it starts from 0 while it's 1 in Matlab. Also, sums = [0]*N initialize a list of a length N, this has to be moved outside of the loop.

points = p 2
sums = [0]*points
for N in range(0, points):
    for index in range(0, N 1):
        sums[N] = sums[N]   (index 1)**p

CodePudding user response:

sums(N) = 0; does not create an array of all zeros, it sets element N of the existing array to 0, and creates additional elements in the array if it not at least of length N.

Because N grows by one each iteration, you could initialize as an empty array before the loop, and append(0) inside the loop:

sums = []
for N in range(1, len(n) 1):
    sums.append(0)

I don’t particularly like the use of enumerate here either, I would:

    for index in range(N)
        sums[index]  = (index   1)**p

(Notice the 1 on the index that was missing in the code in the OP!)

Finally, n is just confusing here. I would:

for N in range(1, points   1):
    …
  • Related