vtsimp
vtsimp

Reputation: 152

Convert a matlab loop to python loop

Im trying to convert a matlab script to python code and i have this loop:

n = 3;
v = zeros(n,n);
for i =1:n
    for j =1:i
        v(i,j) = ((2)^(i-j))*((3)^(j-1));
    end
end

I have managed to convert it to this python code:

import numpy as np

n = 3
v = np.zeros((n,n))
for i in range(1,n+1):
    for j in range(1,i+1):
        v[i-1,j-1] = ((2)**(i-j))*((3)**(j-1))

But it doesn't look nice. Is there a more neat way to write this loop in python? I want to get rid of the range(1,n+1) and write it normally as range(n), but im stuck.

Upvotes: 2

Views: 2517

Answers (1)

NyuB
NyuB

Reputation: 93

for i in range(n):
    for j in range(i+1):
        v[i,j] = ((2)**(i-j))*((3)**(j))

The (i-j) difference won't change if j and i are both reduced by one, you just have to update the last power.

You could also do it in one comprehension list, wich are usefull in python:

v=[[(2**(i-j))*(3**j) if j<=i else 0 for j in range(n)] for i in range(n)]

Upvotes: 2

Related Questions