Home > Enterprise >  Trying to call elements of a matrix within a for loop in Python
Trying to call elements of a matrix within a for loop in Python

Time:12-23

I am working on converting code from Matlab to Python for an astrodynamics research group that I previously joined. I am trying to use Newton's Method to solve for the Eccentric Anomaly of an orbit which requires an iterative process.

I have created the Matrix M outside of the for loop and want to index that matrix within the for loop.

example: (This is how I would write it in Matlab and am looking for how to do this in Python specifically calling the elements of M that coincide with the position of the i value that the for loop is running.)

M = [1, 2, 3, 4]  (where M(1) = 1 and M(3) = 3 and so on) 

for i = 1:4 

   E(i) = 2 - M(i)

end

Result: E = [1, 0, -1, -2]

I would greatly appreciate any suggestions.

Thanks!

CodePudding user response:

I'm not entirely sure I understand you question but is this what you are looking for?

E = [2 - i for i in range(1, 5)]
# [1, 0, -1, -2]

So, if you have an iterable "matrix" M, this would be the solution

M = [1, 2, 3, 4]

E = [2 - i for i in M]
# [1, 0, -1, -2]

CodePudding user response:

A "direct translation" into Python would be:

M = [1, 2, 3, 4]
E = [0, 0, 0, 0]

for i in range(4): ##from 0 to 3
    E[i] = 2 - M[i]
    
print(E)

Note that first index is always 0 in Python I kept the for loop as it may be easier to follow.

  • Related