How to Change into Vector Form

72 views Asked by At

I previously posted the question How to create a Single Vector having 2 Dimensions? , and with some helpful answers I was able to change up my code.

In that previous question I was asked not to separate my values of 'x' and 'v', but use a single vector 'x' that has two dimensions ( i.e. 'x' and 'v' can be handled by x(1) and x(2) ).

With that in mind I was able to change:

# Runge-kutta Method
x = np.empty(N);
v = np.empty(N);
x[0] = x0;
v[0] = v0;

from MY CODE of previous question into:

# Runge-kutta Method
x = np.zeros([2, N]);
x[0,0] = x0
x[1,0] = v0

And switched up the main loop into the following:

for i in range(N - 1):    #MAIN LOOP
    K1x = f1(te[i], x[0, i], x[1, i])
    K1v = f2(te[i], x[0, i], x[1, i])

    K2x = f1(te[i] + h / 2, x[0, i] + h * K1x / 2, x[1, i] + h * K1v / 2)
    K2v = f2(te[i] + h / 2, x[0, i] + h * K1x / 2, x[1, i] + h * K1v / 2)

    K3x = f1(te[i] + h / 2, x[0, i] + h * K2x / 2, x[1, i] + h * K2v / 2)
    K3v = f2(te[i] + h / 2, x[0, i] + h * K2x / 2, x[1, i] + h * K2v / 2)

    K4x = f1(te[i] + h, x[0, i] + h * K3x, x[1, i] + h * K3v)
    K4v = f2(te[i] + h, x[0, i] + h * K3x, x[1, i] + h * K3v)

    x[0, i + 1] = x[0, i] + h / 6 * (K1x + 2 * K2x + 2 * K3x + K4x)
    x[1, i + 1] = x[1, i] + h / 6 * (K1v + 2 * K2v + 2 * K3v + K4v)

The changes worked and provided the results I needed.

Question: My issue is that I'm told that the main loop is not of a vector form. What changes must I make in order to have it in vector form?

1

There are 1 answers

0
Lutz Lehmann On BEST ANSWER

Define

def f(t,x): return np.array([f1(t,*x), f2(t,*x)])

and thus remove every second line in the RK4 loop. The last two for instance would be

    K4 = f(te[i] + h, x[:, i] + h * K3)
    x[:, i + 1] = x[:, i] + h / 6 * (K1 + 2 * K2 + 2 * K3 + K4)