2

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.

1 Answer 1

2
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)]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.