MATLAB: How to solve multi-variable system of ODEs

muli-variable system of odesodeode45systems of odes

I want to solve a system of 4 nonlinear ODEs with two variables x and y. I'm using the code below to try to achieve the solution.
g = @(t, x, y) [
gamma2/2/pi*((x(1)-x(2)) / ((x(1)-x(2))^2 + (y(1)-y(2))^2));
gamma1/2/pi*((x(2)-x(1)) / ((x(1)-x(2))^2 + (y(1)-y(2))^2));
gamma2/2/pi*(-(y(1)-y(2)) / ((x(1)-x(2))^2 + (y(1)-y(2))^2));
gamma1/2/pi*(-(y(2)-y(1)) / ((x(1)-x(2))^2 + (y(1)-y(2))^2))
];
[t, x, y] = ode45(g, [0 200], [y1_0 y2_0 x1_0 x2_0]);
Where gamma1, gamma2, y1_0, y2_0, x1_0, and x2_0 are constants.
Is there a way to use two variable like this? Or do I have to simplify the expression further by assigning y1 = x(1), y2 = x(2), x1 = x(3), x2 = x(4)?

Best Answer

[t z] = ode45(@(t,z)g(t,z,gamma1,gamma2), [0 200], [y1_0 y2_0 x1_0 x2_0]);
function dz = g(t,z,gamma1,gamma2)
y = z(1:2);
x = z(3:4);
dz = [gamma2/2/pi*((x(1)-x(2)) / ((x(1)-x(2))^2 + (y(1)-y(2))^2));
gamma1/2/pi*((x(2)-x(1)) / ((x(1)-x(2))^2 + (y(1)-y(2))^2));
gamma2/2/pi*(-(y(1)-y(2)) / ((x(1)-x(2))^2 + (y(1)-y(2))^2));
gamma1/2/pi*(-(y(2)-y(1)) / ((x(1)-x(2))^2 + (y(1)-y(2))^2))];