2

I want to store the values, calculated in each loop, within an array.

Q2 = np.array([20, 25, 30, 25, 20, 15, 10, 15, 20, 25, 30, 25, 20])
Q3 = np.array([40, 45, 50, 45, 40, 35, 30, 35, 40, 45, 50, 45, 40])


for i in range(13):   
    m = GEKKO()             # create GEKKO model
    x = m.Var(value=0)      # define new variable, initial value=0
    y = m.Var(value=0)      # define new variable, initial value=1
    z = m.Var(value=0)
    m.Equations([x - y == Q2[i], y + z == Q3[i],
                 K[0]*x**2 + K[1]*y**2 - K[2]*z**2 == 0]) # equations
    m.solve(disp=False)     # solve

    print([x.value, y.value, z.value]) # print solution

For each Q(i) I expect to get: x.value(i), y.value(i), z.value(i)

Now it prints all the answers but I want it to store in a matrix.

shiva
  • 5,083
  • 5
  • 23
  • 42
  • Possible duplicate of [Storing values from loop in a list or tuple in Python](https://stackoverflow.com/questions/33553046/storing-values-from-loop-in-a-list-or-tuple-in-python) – Jkind9 Oct 10 '19 at 09:58

3 Answers3

0

If a new pandas dataframe is good for you (as I would do, since it makes the results easiest to understand), you can create an empty dataframe before the loop with:

df = pd.DataFrame(columns=['X', 'Y', 'Z'])

And assign to it in the end of every loop with:

df.loc[len(df)] = (x.value, y.value, z.value)
Aryerez
  • 3,417
  • 2
  • 9
  • 17
0

Similar to the previous answer, you can also do this with numpy arrays and also lists. Nested lists typically are what I use due to simplicity.

Here's an example:

my_list = []
for i in range(3):
    my_list.extend([i,i*2,i*3])
print(my_list)

OUTPUT
[[0, 0, 0], [1, 2, 3], [2, 4, 6]]

Jkind9
  • 742
  • 7
  • 24
-2

You have 2 solutions, either you can create a class containing 3 numbers which will be x, y, and z and create a list of this class. So basically you would have such structure:

container class: int x int y int z

And then you create an object of this class for every couple that you want and then you store them into a list.

Or you can create 3 lists, one for the x, one for the y and one for the z. In which at every iteration you'll store each value in the corresponding list. Since you'll have same index for every list, you just have to have an index value and check in every list the given value.

  • No reason to use lists, and not `pandas dataframe` / `numpy array` structures. – Aryerez Oct 10 '19 at 09:55
  • I don't know about his requirements. Of course you can do it easier with libraries. Main thing about my post is explaining how to do it with python scratch – Jules Spender Oct 10 '19 at 12:07