Home > other >  I formed a for loop, which gives an answer for several inputs,I want to prin those answers in an arr
I formed a for loop, which gives an answer for several inputs,I want to prin those answers in an arr

Time:12-31

for angle in range(0,46,1):
    print("***For the angle: ", angle)
    print("Roll angle", rollangle)
    roll = np.array([[1,0,0],[0,math.cos(angle),-math.sin(angle)],[0,math.sin(angle),math.cos(angle)]])
    print("roll =\n", roll)

I want to print every "roll" values in an array, outside the loop, so, I can use those values again

CodePudding user response:

So you created a loop, got a calculation, and you want to save it so that you can use it later, is that correct?

Just change the range back to 46, I simplified it here for demo purposes!

You can now use that list to access your calculated values.

Being new here, please accept my answer if it helped you! Downvote it if it didnt but please comment why you downvoted!

import numpy as np
import math

List1 = []

for angle in range(0,2,1):
    print("For the angle: ", angle)
    roll = np.array([[1,0,0],[0,math.cos(angle),-math.sin(angle)],[0,math.sin(angle),math.cos(angle)]])
    List1.append(roll)
    print("roll =\n", roll, '\n')

print(List1[1][2][1]) # Accessing a specific value in Roll values for Angle 1
Outputs :
For the angle:  0
roll =
 [[ 1.  0.  0.]
 [ 0.  1. -0.]
 [ 0.  0.  1.]] 

For the angle:  1
roll =
 [[ 1.          0.          0.        ]
 [ 0.          0.54030231 -0.84147098]
 [ 0.          0.84147098  0.54030231]] 

0.8414709848078965

CodePudding user response:

To store the values of "roll" in an array, you can create an empty list before the loop and then append the values of "roll" to the list at each iteration of the loop:

roll_values = []
for angle in range(0, 46, 1):
    print("***For the angle: ", angle)
    print("Roll angle", rollangle)
    roll = np.array([[1,0,0],[0,math.cos(angle),-math.sin(angle)],[0,math.sin(angle),math.cos(angle)]])
    print("roll =\n", roll)
    roll_values.append(roll)

After the loop, you can access the values of "roll" stored in the list by using their indices, for example:

print(roll_values[0])  # prints the first value of roll
print(roll_values[1])  # prints the second value of roll

Alternatively, you can also use a list comprehension to create the list of "roll" values in one line:

roll_values = [np.array([[1,0,0],[0,math.cos(angle),-math.sin(angle)],`[0,math.sin(angle),math.cos(angle)]]) for angle in range(0, 46, 1)]`
  • Related